Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Adding Elements at the Beginning and End of a LinkedList

Java Example – Adding Elements at the Beginning and End of a LinkedList

Java Examples Java Examples

The following example demonstrates how to use the addFirst() and addLast() methods of the LinkedList class to add elements at the beginning and end of the linked list:

Main.java File

import

java

.

util

.

LinkedList

;

public

class

Main

{

public

static

void

main

(

String

[

]

args

)

{

LinkedList

<
String
lList
=
new
LinkedList
<
String
(
)

;

lList

.

add

(

"

1

"

)

;

lList

.

add

(

"

2

"

)

;

lList

.

add

(

"

3

"

)

;

lList

.

add

(

"

4

"

)

;

lList

.

add

(

"

5

"

)

;

System

.

out

.

println

(

lList

)

;

lList

.

addFirst

(

"

0

"

)

;

System

.

out

.

println

(

lList

)

;

lList

.

addLast

(

"

6

"

)

;

System

.

out

.

println

(

lList

)

;

}

}

The output of the above code is:


1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5, 6

Java Examples Java Examples