Beruflich Dokumente
Kultur Dokumente
Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.
As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.
In case of doubly linked list, we can add or remove elements from both side.
LinkedList class declaration
Constructor Description
LinkedList() It is used to construct an empty list.
LinkedList(Collection It is used to construct a list containing the elements of the specified
c) collection, in the order they are returned by the collection's iterator.
Method Description
void add(int index, Object It is used to insert the specified element at the specified position
element) index in a list.
void addFirst(Object o) It is used to insert the given element at the beginning of a list.
void addLast(Object o) It is used to append the given element to the end of a list.
int size() It is used to return the number of elements in a list
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean contains(Object o) It is used to return true if the list contains a specified element.
It is used to remove the first occurence of the specified element
boolean remove(Object o)
in a list.
Object getFirst() It is used to return the first element in a list.
Object getLast() It is used to return the last element in a list.
It is used to return the index in a list of the first occurrence of
int indexOf(Object o) the specified element, or -1 if the list does not contain any
element.
It is used to return the index in a list of the last occurrence of
int lastIndexOf(Object o) the specified element, or -1 if the list does not contain any
element.
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Test it Now
Output:Ravi
Vijay
Ravi
Ajay
https://www.javatpoint.com/java-linkedlist
LinkedList in java
This class consists of the following methods :
1. boolean add(Object element) : It appends the element to the end of the list.
2. void add(int index, Object element): It inserts the element at the position ‘index’ in the
list.
3. void addFirst(Object element) : It inserts the element at the beginning of the list.
4. void addLast(Object element) : It appends the element at the end of the list.
5. boolean contains(Object element) : It returns true if the element is present in the list.
6. Object get(int index) : It returns the element at the position ‘index’ in the list. It throws
‘IndexOutOfBoundsException’ if the index is out of range of the list.
7. int indexOf(Object element) : If element is found, it returns the index of the first
occurrence of the element. Else, it returns -1.
8. Object remove(int index) : It removes the element at the position ‘index’ in this list. It
throws ‘NoSuchElementException’ if the list is empty.
10. void clear() : It removes all of the elements from the list.
import java.util.*;
if(status)
System.out.println("List contains the element 'E' ");
else
System.out.println("List doesn't contain the element 'E'");
Output :
https://www.geeksforgeeks.org/linked-list-in-java/
At the end of this guide, I have linked all the tutorials that I have shared on LinkedList, refer
them in the given order to understand this topic fully.
Example of LinkedList in Java
import java.util.*;
public class LinkedListExample {
public static void main(String args[]) {
Output:
For all the examples in the below methods, consider llistobj as a reference for
LinkedList<String>.
1) boolean add(Object item): It adds the item at the end of the list.
llistobj.add("Hello");
It would add the string “Hello” at the end of the linked list.
2) void add(int index, Object item): It adds an item at the given index of the the list.
llistobj.add(2, "bye");
This will add the string “bye” at the 3rd position( 2 index is 3rd position as index starts with
0).
3) boolean addAll(Collection c): It adds all the elements of the specified collection c to the
list. It throws NullPointerException if the specified collection is null. Consider the below
example –
This piece of code would add all the elements of ArrayList to the LinkedList.
4) boolean addAll(int index, Collection c): It adds all the elements of collection c to the list
starting from a give index in the list. It throws NullPointerException if the collection c is null
and IndexOutOfBoundsException when the specified index is out of the range.
llistobj.add(5, arraylist);
It would add all the elements of the ArrayList to the LinkedList starting from position 6
(index 5).
5) void addFirst(Object item): It adds the item (or element) at the first position in the list.
llistobj.addFirst("text");
6) void addLast(Object item): It inserts the specified item at the end of the list.
llistobj.addLast("Chaitanya");
This statement will add a string “Chaitanya” at the end position of the linked list.
llistobj.clear();
For e.g. My linkedList has four items: text1, text2, text3 and text4.
9) boolean contains(Object item): It checks whether the given item is present in the list or
not. If the item is present then it returns true else false.
It will check whether the string “TestString” exist in the list or not.
10) Object get(int index): It returns the item of the specified index from the list.
11) Object getFirst(): It fetches the first item from the list.
12) Object getLast(): It fetches the last item from the list.
13) int indexOf(Object item): It returns the index of the specified item.
llistobj.indexOf("bye");
14) int lastIndexOf(Object item): It returns the index of last occurrence of the specified
element.
integer variable pos will be having the index of last occurrence of string “hello”.
15) Object poll(): It returns and removes the first item of the list.
Object o = llistobj.poll();
16) Object pollFirst(): same as poll() method. Removes the first item of the list.
Object o = llistobj.pollFirst();
17) Object pollLast(): It returns and removes the last element of the list.
Object o = llistobj.pollLast();
llistobj.remove();
19) Object remove(int index): It removes the item from the list which is present at the
specified index.
llistobj.remove(4);
20) Object remove(Object obj): It removes the specified object from the list.
llistobj.remove("Test Item");
21) Object removeFirst(): It removes the first item from the list.
llistobj.removeFirst();
llistobj.removeLast();
llistobj.removeFirstOccurrence("text");
It will remove the first occurrence of the string “text” from the list.
llistobj.removeLastOccurrence("String1);
25) Object set(int index, Object item): It updates the item of specified index with the give
value.
llistobj.set(2, "Test");
llistobj.size();
https://beginnersbook.com/2013/12/linkedlist-in-java-with-example/
Linked Lists
Introduction
One disadvantage of using arrays to store data is that arrays are static structures and therefore
cannot be easily extended or reduced to fit the data set. Arrays are also expensive to maintain new
insertions and deletions. In this chapter we consider another data structure called Linked Lists that
addresses some of the limitations of arrays.
A linked list is a linear data structure where each element is a separate object.
Each element (we will call it a node) of a list is comprising of two items - the data and a reference to
the next node. The last node has a reference to null. The entry point into a linked list is called the
head of the list. It should be noted that head is not a separate node, but the reference to the first
node. If the list is empty then the head is a null reference.
A linked list is a dynamic data structure. The number of nodes in a list is not fixed and can
grow and shrink on demand. Any application which has to deal with an unknown number of
objects will need to use a linked list.
One disadvantage of a linked list against an array is that it does not allow direct access to the
individual elements. If you want to access a particular item then you have to start at the head
and follow the references until you get to that item.
Another disadvantage is that a linked list uses more memory compare with an array - we
extra 4 bytes (on 32-bit CPU) to store a reference to the next node.
A doubly linked list is a list that has two references, one to the next node and another to
previous node.
Another important type of a linked list is called a circular linked list where last node of the list points
back to the first node (or the head) of the list.
In Java you are allowed to define a class (say, B) inside of another class (say, A). The class A is called
the outer class, and the class B is called the inner class. The purpose of inner classes is purely to be
used internally as helper classes. Here is the LinkedList class with the inner Node class
We implement the LinkedList class with two inner classes: static Node class and non-static
LinkedListIterator class. See LinkedList.java for a complete implementation.
Examples
Let us assume the singly linked list above and trace down the effect of each fragment below.
The list is restored to its initial state before each line executes
1. head = head.next;
2.
3. head.next = head.next.next;
4.
5. head.next.next.next.next = head;
6.
The method creates a node and prepends it at the beginning of the list.
Traversing
Start with the head and access each node until you reach null. Do not change the head
reference.
The method appends the node to the end of the list. This requires traversing, but make sure
you stop at the last node
Inserting "after"
Find a node containing "key" and insert a new node after it. In the picture below, we insert a
new node after "e":
if(tmp != null)
tmp.next = new Node<AnyType>(toInsert, tmp.next);
}
Inserting "before"
Find a node containing "key" and insert a new node before that node. In the picture below,
we insert a new node before "a":
For the sake of convenience, we maintain two references prev and cur. When we move along the
list we shift these two references, keeping prev one step before cur. We continue until cur
reaches the node before which we need to make an insertion. If cur reaches null, we don't insert,
otherwise we insert a new node between prev and cur.
Deletion
Find a node containing "key" and delete it. In the picture below we delete a node containing
"A"
The algorithm is similar to insert "before" algorithm. It is convinient to use two references prev and
cur. When we move along the list we shift these two references, keeping prev one step before
cur. We continue until cur reaches the node which we need to delete. There are three exceptional
cases, we need to take care of:
1. list is empty
2. delete the head node
3. node is not in the list
if( head.data.equals(key) )
{
head = head.next;
return;
}
Iterator
The whole idea of the iterator is to provide an access to a private aggregated data and at the
same moment hiding the underlying representation. An iterator is Java is an object, and
therefore it's implementation requires creating a class that implements the Iterator interface.
Usually such class is implemented as a private inner class. The Iterator interface contains the
following methods:
In this section we implement the Iterator in the LinkedList class. First of all we add a new method to
the LinkedList class:
public Iterator<AnyType> iterator()
{
return new LinkedListIterator();
}
public LinkedListIterator()
{
nextNode = head;
}
...
}
The LinkedListIterator class must provide implementations for next() and hasNext()
methods. Here is the next() method:
Cloning
Like for any other objects, we need to learn how to clone linked lists. If we simply use the
clone() method from the Object class, we will get the following structure called a "shallow"
copy:
The Object's clone() will create a copy of the first node, and share the rest. This is not exactly
what we mean by "a copy of the object". What we actually want is a copy represented by the
picture below
Since out data is immutable it's ok to have data shared between two linked lists. There are a
few ideas to implement linked list copying. The simplest one is to traverse the original list
and copy each node by using the addFirst() method. When this is finished, you will have a
new list in the reverse order. Finally, we will have to reverse the list:
return twin.reverse();
}
A better way involves using a tail reference for the new list, adding each new node after the
last node.
while(tmp.next != null)
{
tmp = tmp.next;
tmpTwin.next = new Node<AnyType>(tmp.data, null);
tmpTwin = tmpTwin.next;
}
return twin;
}
Applications
Polynomial Algebra
The biggest integer that we can store in a variable of the type int is 231 - 1 on 32-but CPU.
You can easily verify this by the following operations:
int prod=1;
for(int i = 1; i <=; 31; i ++)
prod *= 2;
System.out.println(prod);
This code doesn't produce an error, it produces a result! The printed value is a negative
integer -2147483648 = -231. If the value becomes too large, Java saves only the low order
32 (or 64 for longs) bits and throws the rest away.
In real life applications we need to deal with integers that are larger than 64 bits (the size of a
long). To manipulate with such big numbers, we will be using a linked list data structure.
First we observe that each integer can be expressed in the decimal system of notation.
We will write an application that manipulates polynomials in one variable with real
coefficients.Among many operations on polynomials, we implement addition, multiplication,
differentiation and evaluation. A polynomial willbe represented as a linked list, where each
node has an integer degree, a double coefficient and a reference to the next term. The final
node will have a null reference to indicate the end of the list. Here is a linked link
representation for the above polynomial:
The terms are kept in order from smallest to largest exponent. See Polynomial.java for
details.
https://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html
The LinkedList Class
The LinkedList class extends AbstractSequentialList and implements the List interface. It
provides a linked-list data structure.
LinkedList( )
1
This constructor builds an empty linked list.
2 LinkedList(Collection c)
This constructor builds a linked list that is initialized with the elements of the collection c.
Apart from the methods inherited from its parent classes, LinkedList defines following
methods −
Example
import java.util.*;
public class LinkedListDemo {
Output
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
https://www.tutorialspoint.com/java/java_linkedlist_class.htm
/*******************************************************************
********
* A Linked List class with a private static inner Node class.
*
********************************************************************
*********/
import java.util.*;
/**
* Constructs an empty list
*/
public LinkedList()
{
head = null;
}
/**
* Returns true if the list is empty
*
*/
public boolean isEmpty()
{
return head == null;
}
/**
* Inserts a new node at the beginning of this list.
*
*/
public void addFirst(AnyType item)
{
head = new Node<AnyType>(item, head);
}
/**
* Returns the first element in the list.
*
*/
public AnyType getFirst()
{
if(head == null) throw new NoSuchElementException();
return head.data;
}
/**
* Removes the first element in the list.
*
*/
public AnyType removeFirst()
{
AnyType tmp = getFirst();
head = head.next;
return tmp;
}
/**
* Inserts a new node to the end of this list.
*
*/
public void addLast(AnyType item)
{
if( head == null)
addFirst(item);
else
{
Node<AnyType> tmp = head;
while(tmp.next != null) tmp = tmp.next;
return tmp.data;
}
/**
* Removes all nodes from the list.
*
*/
public void clear()
{
head = null;
}
/**
* Returns true if this list contains the specified element.
*
*/
public boolean contains(AnyType x)
{
for(AnyType tmp : this)
if(tmp.equals(x)) return true;
return false;
}
/**
* Returns the data at the specified position in the list.
*
*/
public AnyType get(int pos)
{
if (head == null) throw new IndexOutOfBoundsException();
return tmp.data;
}
/**
* Returns a string representation
*
*/
public String toString()
{
StringBuffer result = new StringBuffer();
for(Object x : this)
result.append(x + " ");
return result.toString();
}
/**
* Inserts a new node after a node containing the key.
*
*/
public void insertAfter(AnyType key, AnyType toInsert)
{
Node<AnyType> tmp = head;
if(tmp != null)
tmp.next = new Node<AnyType>(toInsert, tmp.next);
}
/**
* Inserts a new node before a node containing the key.
*
*/
public void insertBefore(AnyType key, AnyType toInsert)
{
if(head == null) return;
if(head.data.equals(key))
{
addFirst(toInsert);
return;
}
if( head.data.equals(key) )
{
head = head.next;
return;
}
if(cur == null)
throw new RuntimeException("cannot delete");
return twin;
}
/**
* Returns a deep copy of the list
* Complexity: O(n)
*/
public LinkedList<AnyType> copy2()
{
LinkedList<AnyType> twin = new LinkedList<AnyType>();
Node<AnyType> tmp = head;
while(tmp != null)
{
twin.addFirst( tmp.data );
tmp = tmp.next;
}
return twin.reverse();
}
/**
* Reverses the list
* Complewxity: O(n)
*/
public LinkedList<AnyType> reverse()
{
LinkedList<AnyType> list = new LinkedList<AnyType>();
Node<AnyType> tmp = head;
while(tmp != null)
{
list.addFirst( tmp.data );
tmp = tmp.next;
}
return list;
}
/**
* Returns a deep copy of the immutable list
* It uses a tail reference.
* Complexity: O(n)
*/
public LinkedList<AnyType> copy3()
{
LinkedList<AnyType> twin = new LinkedList<AnyType>();
Node<AnyType> tmp = head;
if(head==null) return null;
twin.head = new Node<AnyType>(head.data, null);
Node<AnyType> tmpTwin = twin.head;
while(tmp.next != null)
{
tmp = tmp.next;
tmpTwin.next = new Node<AnyType>(tmp.data, null);
tmpTwin = tmpTwin.next;
}
return twin;
}
/*******************************************************
*
* The Node class
*
********************************************************/
private static class Node<AnyType>
{
private AnyType data;
private Node<AnyType> next;
/*******************************************************
*
* The Iterator class
*
********************************************************/
public LinkedListIterator()
{
nextNode = head;
}
System.out.println(list.get(0));
// System.out.println(list.get(4)); //exception
list.addLast("s");
Iterator itr = list.iterator();
while(itr.hasNext())
System.out.print(itr.next() + " ");
System.out.println();
for(Object x : list)
System.out.print(x + " ");
System.out.println();
list.insertAfter("e", "ee");
System.out.println(list);
System.out.println(list.getLast());
list.insertBefore("h", "yy");
System.out.println(list);
list.remove("p");
System.out.println(list);
}
}
Java Program to Implement Singly Linked
List
This is a Java Program to implement a Singly Linked List. A linked list is a data structure
consisting of a group of nodes which together represent a sequence. Under the simplest form,
each node is composed of a data and a reference (in other words, a link) to the next node in
the sequence. This structure allows for efficient insertion or removal of elements from any
position in the sequence. In a singly linked list each node has only one link which points to
the next node in the list.
Here is the source code of the Java program to implement Singly Linked List. The Java
program is successfully compiled and run on a Windows system. The program output is also
shown below.
1. /*
2. * Java Program to Implement Singly Linked List
3. */
4.
5. import java.util.Scanner;
6.
7. /* Class Node */
8. class Node
9. {
10. protected int data;
11. protected Node link;
12.
13. /* Constructor */
14. public Node()
15. {
16. link = null;
17. data = 0;
18. }
19. /* Constructor */
20. public Node(int d,Node n)
21. {
22. data = d;
23. link = n;
24. }
25. /* Function to set link to next Node */
26. public void setLink(Node n)
27. {
28. link = n;
29. }
30. /* Function to set data to current Node */
31. public void setData(int d)
32. {
33. data = d;
34. }
35. /* Function to get link to next node */
36. public Node getLink()
37. {
38. return link;
39. }
40. /* Function to get data from current Node */
41. public int getData()
42. {
43. return data;
44. }
45. }
46.
47. /* Class linkedList */
48. class linkedList
49. {
50. protected Node start;
51. protected Node end ;
52. public int size ;
53.
54. /* Constructor */
55. public linkedList()
56. {
57. start = null;
58. end = null;
59. size = 0;
60. }
61. /* Function to check if list is empty */
62. public boolean isEmpty()
63. {
64. return start == null;
65. }
66. /* Function to get size of list */
67. public int getSize()
68. {
69. return size;
70. }
71. /* Function to insert an element at begining */
72. public void insertAtStart(int val)
73. {
74. Node nptr = new Node(val, null);
75. size++ ;
76. if(start == null)
77. {
78. start = nptr;
79. end = start;
80. }
81. else
82. {
83. nptr.setLink(start);
84. start = nptr;
85. }
86. }
87. /* Function to insert an element at end */
88. public void insertAtEnd(int val)
89. {
90. Node nptr = new Node(val,null);
91. size++ ;
92. if(start == null)
93. {
94. start = nptr;
95. end = start;
96. }
97. else
98. {
99. end.setLink(nptr);
100. end = nptr;
101. }
102. }
103. /* Function to insert an element at position */
104. public void insertAtPos(int val , int pos)
105. {
106. Node nptr = new Node(val, null);
107. Node ptr = start;
108. pos = pos - 1 ;
109. for (int i = 1; i < size; i++)
110. {
111. if (i == pos)
112. {
113. Node tmp = ptr.getLink() ;
114. ptr.setLink(nptr);
115. nptr.setLink(tmp);
116. break;
117. }
118. ptr = ptr.getLink();
119. }
120. size++ ;
121. }
122. /* Function to delete an element at position */
123. public void deleteAtPos(int pos)
124. {
125. if (pos == 1)
126. {
127. start = start.getLink();
128. size--;
129. return ;
130. }
131. if (pos == size)
132. {
133. Node s = start;
134. Node t = start;
135. while (s != end)
136. {
137. t = s;
138. s = s.getLink();
139. }
140. end = t;
141. end.setLink(null);
142. size --;
143. return;
144. }
145. Node ptr = start;
146. pos = pos - 1 ;
147. for (int i = 1; i < size - 1; i++)
148. {
149. if (i == pos)
150. {
151. Node tmp = ptr.getLink();
152. tmp = tmp.getLink();
153. ptr.setLink(tmp);
154. break;
155. }
156. ptr = ptr.getLink();
157. }
158. size-- ;
159. }
160. /* Function to display elements */
161. public void display()
162. {
163. System.out.print("\nSingly Linked List = ");
164. if (size == 0)
165. {
166. System.out.print("empty\n");
167. return;
168. }
169. if (start.getLink() == null)
170. {
171. System.out.println(start.getData() );
172. return;
173. }
174. Node ptr = start;
175. System.out.print(start.getData()+ "->");
176. ptr = start.getLink();
177. while (ptr.getLink() != null)
178. {
179. System.out.print(ptr.getData()+ "->");
180. ptr = ptr.getLink();
181. }
182. System.out.print(ptr.getData()+ "\n");
183. }
184. }
185.
186. /* Class SinglyLinkedList */
187. public class SinglyLinkedList
188. {
189. public static void main(String[] args)
190. {
191. Scanner scan = new Scanner(System.in);
192. /* Creating object of class linkedList */
193. linkedList list = new linkedList();
194. System.out.println("Singly Linked List Test\n");
195. char ch;
196. /* Perform list operations */
197. do
198. {
199. System.out.println("\nSingly Linked List
Operations\n");
200. System.out.println("1. insert at begining");
201. System.out.println("2. insert at end");
202. System.out.println("3. insert at position");
203. System.out.println("4. delete at position");
204. System.out.println("5. check empty");
205. System.out.println("6. get size");
206. int choice = scan.nextInt();
207. switch (choice)
208. {
209. case 1 :
210. System.out.println("Enter integer element to
insert");
211. list.insertAtStart( scan.nextInt() );
212. break;
213. case 2 :
214. System.out.println("Enter integer element to
insert");
215. list.insertAtEnd( scan.nextInt() );
216. break;
217. case 3 :
218. System.out.println("Enter integer element to
insert");
219. int num = scan.nextInt() ;
220. System.out.println("Enter position");
221. int pos = scan.nextInt() ;
222. if (pos <= 1 || pos > list.getSize() )
223. System.out.println("Invalid position\n");
224. else
225. list.insertAtPos(num, pos);
226. break;
227. case 4 :
228. System.out.println("Enter position");
229. int p = scan.nextInt() ;
230. if (p < 1 || p > list.getSize() )
231. System.out.println("Invalid position\n");
232. else
233. list.deleteAtPos(p);
234. break;
235. case 5 :
236. System.out.println("Empty status = "+
list.isEmpty());
237. break;
238. case 6 :
239. System.out.println("Size = "+ list.getSize() +"
\n");
240. break;
241. default :
242. System.out.println("Wrong Entry \n ");
243. break;
244. }
245. /* Display List */
246. list.display();
247. System.out.println("\nDo you want to continue (Type y
or n) \n");
248. ch = scan.next().charAt(0);
249. } while (ch == 'Y'|| ch == 'y');
250. }
251. }
Singly Linked List Test
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
5
Empty status = true
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
5
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
7
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
2
Enter integer element to insert
4
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
2
Enter integer element to insert
2
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
9
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
3
Enter integer element to insert
3
Enter position
3
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
3
Enter integer element to insert
2
Enter position
2
y
Singly Linked List Operations
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
6
Size = 7
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
4
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
2
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
3
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
2
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
1
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
5
Empty status = true