Sei sulla pagina 1di 38

Java LinkedList class

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.

The important points about Java LinkedList are:

 Java LinkedList class can contain duplicate elements.


 Java LinkedList class maintains insertion order.
 Java LinkedList class is non synchronized.
 In Java LinkedList class, manipulation is fast because no shifting needs to be
occurred.
 Java LinkedList class can be used as list, stack or queue.

Hierarchy of LinkedList class

As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.

Doubly Linked List

In case of doubly linked list, we can add or remove elements from both side.
LinkedList class declaration

Let's see the declaration for java.util.LinkedList class.

public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque


<E>, Cloneable, Serializable

Constructors of Java LinkedList

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.

Methods of Java LinkedList

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.

Java LinkedList Example


import java.util.*;
public class TestCollection7{
public static void main(String args[]){

LinkedList<String> al=new LinkedList<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Test it Now
Output:Ravi
Vijay
Ravi
Ajay

Java LinkedList Example: Book


import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quant
ity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class LinkedListExample {
public static void main(String[] args) {
//Creating list of Books
List<Book> list=new LinkedList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc
Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.q
uantity);
}
}
}
Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

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.

9. int size() : It returns the number of elements in this list.

10. void clear() : It removes all of the elements from the list.

// Java code for Linked List implementation

import java.util.*;

public class Test


{
public static void main(String args[])
{
// Creating object of class linked list
LinkedList<String> object = new LinkedList<String>();

// Adding elements to the linked list


object.add("A");
object.add("B");
object.addLast("C");
object.addFirst("D");
object.add(2, "E");
object.add("F");
object.add("G");
System.out.println("Linked list : " + object);

// Removing elements from the linked list


object.remove("B");
object.remove(3);
object.removeFirst();
object.removeLast();
System.out.println("Linked list after deletion: " + object);

// Finding elements in the linked list


boolean status = object.contains("E");

if(status)
System.out.println("List contains the element 'E' ");
else
System.out.println("List doesn't contain the element 'E'");

// Number of elements in the linked list


int size = object.size();
System.out.println("Size of linked list = " + size);

// Get and set elements from linked list


Object element = object.get(2);
System.out.println("Element returned by get() : " + element);
object.set(2, "Y");
System.out.println("Linked list after change : " + object);
}
}

Output :

Linked list : [D, A, E, B, C, F, G]


Linked list after deletion: [A, E, F]
List contains the element 'E'
Size of linked list = 3
Element returned by get() : F
Linked list after change : [A, E, Y]

https://www.geeksforgeeks.org/linked-list-in-java/

LinkedList in Java with Example


LinkedList is a doubly-linked list implementation of the List and Deque interfaces.
LinkedList allows for constant-time insertions or removals using iterators, but only sequential
access of elements. In other words, LinkedList can be searched forward and backward but the
time it takes to traverse the list is directly proportional to the size of the list.

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[]) {

/* Linked List Declaration */


LinkedList<String> linkedlist = new LinkedList<String>();

/*add(String Element) is used for adding


* the elements to the linked list*/
linkedlist.add("Item1");
linkedlist.add("Item5");
linkedlist.add("Item3");
linkedlist.add("Item6");
linkedlist.add("Item2");

/*Display Linked List Content*/


System.out.println("Linked List Content: " +linkedlist);

/*Add First and Last Element*/


linkedlist.addFirst("First Item");
linkedlist.addLast("Last Item");
System.out.println("LinkedList Content after addition: "
+linkedlist);

/*This is how to get and set Values*/


Object firstvar = linkedlist.get(0);
System.out.println("First element: " +firstvar);
linkedlist.set(0, "Changed first item");
Object firstvar2 = linkedlist.get(0);
System.out.println("First element after update by set method: "
+firstvar2);

/*Remove first and last element*/


linkedlist.removeFirst();
linkedlist.removeLast();
System.out.println("LinkedList after deletion of first and last
element: " +linkedlist);

/* Add to a Position and remove from a position*/


linkedlist.add(0, "Newly added item");
linkedlist.remove(2);
System.out.println("Final Content: " +linkedlist);
}
}

Output:

Linked List Content: [Item1, Item5, Item3, Item6, Item2]


LinkedList Content after addition: [First Item, Item1, Item5, Item3, Item6,
Item2, Last Item]
First element: First Item
First element after update by set method: Changed first item
LinkedList after deletion of first and last element: [Item1, Item5, Item3,
Item6, Item2]
Final Content: [Newly added item, Item1, Item3, Item6, Item2]
Methods of LinkedList class:

For all the examples in the below methods, consider llistobj as a reference for
LinkedList<String>.

LinkedList<String> llistobj = new 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 –

LinkedList<String> llistobj = new LinkedList<String>();


ArrayList<String> arraylist= new ArrayList<String>();
arraylist.add("String1");
arraylist.add("String2");
llistobj.addAll(arraylist);

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");

It would add the string “text” at the beginning of the list.

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.

7) void clear(): It removes all the elements of a list.

llistobj.clear();

8) Object clone(): It returns the copy of the list.

For e.g. My linkedList has four items: text1, text2, text3 and text4.

Object str= llistobj.clone();


System.out.println(str);

Output: The output of above code would be:

[text1, text2, text3, 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.

boolean var = llistobj.contains("TestString");

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.

Object var = llistobj.get(2);

It will fetch the 3rd item from the list.

11) Object getFirst(): It fetches the first item from the list.

Object var = llistobj.getFirst();

12) Object getLast(): It fetches the last item from the list.

Object var= llistobj.getLast();

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.

int pos = llistobj.lastIndexOf("hello);

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();

18) Object remove(): It removes the first element of the list.

llistobj.remove();

19) Object remove(int index): It removes the item from the list which is present at the
specified index.

llistobj.remove(4);

It will remove the 5th element from the list.

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();

22) Object removeLast(): It removes the last item of the list.

llistobj.removeLast();

23) Object removeFirstOccurrence(Object item): It removes the first occurrence of the


specified item.

llistobj.removeFirstOccurrence("text");

It will remove the first occurrence of the string “text” from the list.

24) Object removeLastOccurrence(Object item): It removes the last occurrence of the


given element.

llistobj.removeLastOccurrence("String1);

It will remove the last occurrence of string “String1”.

25) Object set(int index, Object item): It updates the item of specified index with the give
value.

llistobj.set(2, "Test");

It will update the 3rd element with the string “Test”.


26) int size(): It returns the number of elements of the list.

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.

Types of Linked Lists

A singly linked list is described above

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.

The Node class

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

private static class Node<AnyType>


{
private AnyType data;
private Node<AnyType> next;

public Node(AnyType data, Node<AnyType> next)


{
this.data = data;
this.next = next;
}
}
An inner class is a member of its enclosing class and has access to other members (inclusing private)
of the outer class, And vise versa, the outer class can have a direct access to all members of the
inner class. An inner class can be declared private, public, protected, or package private. There are
two kind of inner classes: static and non-static. A static inner class cannot refer directly to instance
variables or methods defined in its outer class: it can use them only through an object reference.

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.

Linked List Operations


addFirst

The method creates a node and prepends it at the beginning of the list.

public void addFirst(AnyType item)


{
head = new Node<AnyType>(item, head);
}

Traversing

Start with the head and access each node until you reach null. Do not change the head
reference.

Node tmp = head;

while(tmp != null) tmp = tmp.next;


addLast

The method appends the node to the end of the list. This requires traversing, but make sure
you stop at the last node

public void addLast(AnyType item)


{
if(head == null) addFirst(item);
else
{
Node<AnyType> tmp = head;
while(tmp.next != null) tmp = tmp.next;

tmp.next = new Node<AnyType>(item, null);


}
}

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":

public void insertAfter(AnyType key, AnyType toInsert)


{
Node<AnyType> tmp = head;
while(tmp != null && !tmp.data.equals(key)) tmp = tmp.next;

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.

Examine this implementation

public void insertBefore(AnyType key, AnyType toInsert)


{
if(head == null) return null;
if(head.data.equals(key))
{
addFirst(toInsert);
return;
}

Node<AnyType> prev = null;


Node<AnyType> cur = head;

while(cur != null && !cur.data.equals(key))


{
prev = cur;
cur = cur.next;
}
//insert between cur and prev
if(cur != null) prev.next = new Node<AnyType>(toInsert, 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

public void remove(AnyType key)


{
if(head == null) throw new RuntimeException("cannot delete");

if( head.data.equals(key) )
{
head = head.next;
return;
}

Node<AnyType> cur = head;


Node<AnyType> prev = null;

while(cur != null && !cur.data.equals(key) )


{
prev = cur;
cur = cur.next;
}

if(cur == null) throw new RuntimeException("cannot delete");

//delete cur node


prev.next = cur.next;
}

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:

 AnyType next() - returns the next element in the container


 boolean hasNext() - checks if there is a next element
 void remove() - (optional operation).removes the element returned by next()

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();
}

Here LinkedListIterator is a private class inside the LinkedList class


private class LinkedListIterator implements Iterator<AnyType>
{
private Node<AnyType> nextNode;

public LinkedListIterator()
{
nextNode = head;
}
...
}
The LinkedListIterator class must provide implementations for next() and hasNext()
methods. Here is the next() method:

public AnyType next()


{
if(!hasNext()) throw new NoSuchElementException();
AnyType res = nextNode.data;
nextNode = nextNode.next;
return res;
}

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:

public Object copy()


{
LinkedList<AnyType> twin = new LinkedList<AnyType>();
Node<AnyType> tmp = head;
while(tmp != null)
{
twin.addFirst( tmp.data );
tmp = tmp.next;
}

return twin.reverse();
}

A better way involves using a tail reference for the new list, adding each new node after the
last node.

public LinkedList<AnyType> copy3()


{
if(head==null) return null;
LinkedList<AnyType> twin = new LinkedList<AnyType>();
Node tmp = head;
twin.head = new Node<AnyType>(head.data, null);
Node tmpTwin = twin.head;

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.

937 = 9*102 + 3*101 + 7*100

2011 = 2*103 + 0*102 + 1*101 + 1*100

Now, if we replace a decimal base 10 by a character, say 'x', we obtain a univariate


polynomial, such as

0.45 - 1.89 x2 + 3.4 x5 + 9 x16

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.

Following are the constructors supported by the LinkedList class.

Sr.No. Constructor & Description

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 −

Sr.No. Method & Description

void add(int index, Object element)


1
Inserts the specified element at the specified position index in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >
size()).
boolean add(Object o)
2
Appends the specified element to the end of this list.
boolean addAll(Collection c)
3
Appends all of the elements in the specified collection to the end of this list, in the
order that they are returned by the specified collection's iterator. Throws
NullPointerException if the specified collection is null.
boolean addAll(int index, Collection c)
4
Inserts all of the elements in the specified collection into this list, starting at the
specified position. Throws NullPointerException if the specified collection is null.
void addFirst(Object o)
5
Inserts the given element at the beginning of this list.
void addLast(Object o)
6
Appends the given element to the end of this list.
void clear()
7
Removes all of the elements from this list.
Object clone()
8
Returns a shallow copy of this LinkedList.
boolean contains(Object o)
9
Returns true if this list contains the specified element. More formally, returns true if
and only if this list contains at least one element e such that (o==null ? e==null :
o.equals(e)).
Object get(int index)
10
Returns the element at the specified position in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0 || index
>= size()).
Object getFirst()
11
Returns the first element in this list. Throws NoSuchElementException if this list is
empty.
Object getLast()
12
Returns the last element in this list. Throws NoSuchElementException if this list is
empty.
int indexOf(Object o)
13
Returns the index in this list of the first occurrence of the specified element, or -1 if the
list does not contain this element.
int lastIndexOf(Object o)
14
Returns the index in this list of the last occurrence of the specified element, or -1 if the
list does not contain this element.
ListIterator listIterator(int index)
15
Returns a list-iterator of the elements in this list (in proper sequence), starting at the
specified position in the list. Throws IndexOutOfBoundsException if the specified
index is out of range (index < 0 || index >= size()).
Object remove(int index)
16
Removes the element at the specified position in this list. Throws
NoSuchElementException if this list is empty.
boolean remove(Object o)
17
Removes the first occurrence of the specified element in this list. Throws
NoSuchElementException if this list is empty. Throws IndexOutOfBoundsException if
the specified index is out of range (index < 0 || index >= size()).
Object removeFirst()
18
Removes and returns the first element from this list. Throws
NoSuchElementException if this list is empty.
Object removeLast()
19
Removes and returns the last element from this list. Throws NoSuchElementException
if this list is empty.
Object set(int index, Object element)
20
Replaces the element at the specified position in this list with the specified element.
Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 ||
index >= size()).
int size()
21
Returns the number of elements in this list.
Object[] toArray()
22
Returns an array containing all of the elements in this list in the correct order. Throws
NullPointerException if the specified array is null.
Object[] toArray(Object[] a)
23
Returns an array containing all of the elements in this list in the correct order; the
runtime type of the returned array is that of the specified array.

Example

The following program illustrates several of the methods supported by LinkedList

import java.util.*;
public class LinkedListDemo {

public static void main(String args[]) {


// create a linked list
LinkedList ll = new LinkedList();

// add elements to the linked list


ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);

// remove elements from the linked list


ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: " + ll);

// remove first and last elements


ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: " + ll);

// get and set a value


Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}

This will produce the following result −

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.*;

public class LinkedList<AnyType> implements Iterable<AnyType>


{
private Node<AnyType> head;

/**
* 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;

tmp.next = new Node<AnyType>(item, null);


}
}
/**
* Returns the last element in the list.
*
*/
public AnyType getLast()
{
if(head == null) throw new NoSuchElementException();

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();

Node<AnyType> tmp = head;


for (int k = 0; k < pos; k++) tmp = tmp.next;

if( tmp == 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;

while(tmp != null && !tmp.data.equals(key)) tmp = tmp.next;

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;
}

Node<AnyType> prev = null;


Node<AnyType> cur = head;

while(cur != null && !cur.data.equals(key))


{
prev = cur;
cur = cur.next;
}
//insert between cur and prev
if(cur != null)
prev.next = new Node<AnyType>(toInsert, cur);
}
/**
* Removes the first occurrence of the specified element in this
list.
*
*/
public void remove(AnyType key)
{
if(head == null)
throw new RuntimeException("cannot delete");

if( head.data.equals(key) )
{
head = head.next;
return;
}

Node<AnyType> cur = head;


Node<AnyType> prev = null;

while(cur != null && !cur.data.equals(key) )


{
prev = cur;
cur = cur.next;
}

if(cur == null)
throw new RuntimeException("cannot delete");

//delete cur node


prev.next = cur.next;
}
/**
* Returns a deep copy of the list
* Complexity: O(n^2)
*/
public LinkedList<AnyType> copy1()
{
LinkedList<AnyType> twin = new LinkedList<AnyType>();
Node<AnyType> tmp = head;
while(tmp != null)
{
twin.addLast( tmp.data );
tmp = tmp.next;
}

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;

public Node(AnyType data, Node<AnyType> next)


{
this.data = data;
this.next = next;
}
}

/*******************************************************
*
* The Iterator class
*
********************************************************/

public Iterator<AnyType> iterator()


{
return new LinkedListIterator();
}

private class LinkedListIterator implements Iterator<AnyType>


{
private Node<AnyType> nextNode;

public LinkedListIterator()
{
nextNode = head;
}

public boolean hasNext()


{
return nextNode != null;
}

public AnyType next()


{
if (!hasNext()) throw new NoSuchElementException();
AnyType res = nextNode.data;
nextNode = nextNode.next;
return res;
}

public void remove() { throw new


UnsupportedOperationException(); }
}

/***** Include the main() for testing and debugging *****/

public static void main(String[] args)


{
LinkedList<String> list = new LinkedList <String>();
list.addFirst("p");
list.addFirst("a");
list.addFirst("e");
list.addFirst("h");
System.out.println(list);

LinkedList<String> twin = list.copy3();


System.out.println(twin);

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

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
5
Empty status = true

Singly Linked List = empty

Do you want to continue (Type y or n)

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
1
Enter integer element to insert
5

Singly Linked List = 5

Do you want to continue (Type y or n)

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
1
Enter integer element to insert
7

Singly Linked List = 7->5

Do you want to continue (Type y or n)

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
2
Enter integer element to insert
4

Singly Linked List = 7->5->4

Do you want to continue (Type y or n)

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
2
Enter integer element to insert
2

Singly Linked List = 7->5->4->2

Do you want to continue (Type y or n)


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
1
Enter integer element to insert
9

Singly Linked List = 9->7->5->4->2

Do you want to continue (Type y or n)

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
3
Enter integer element to insert
3
Enter position
3

Singly Linked List = 9->7->3->5->4->2

Do you want to continue (Type y or n)

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
3
Enter integer element to insert
2
Enter position
2

Singly Linked List = 9->2->7->3->5->4->2

Do you want to continue (Type y or n)

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

Singly Linked List = 9->2->7->3->5->4->2

Do you want to continue (Type y or n)

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
4
Enter position
4

Singly Linked List = 9->2->7->5->4->2

Do you want to continue (Type y or n)

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
4
Enter position
2

Singly Linked List = 9->7->5->4->2

Do you want to continue (Type y or n)

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
4
Enter position
1

Singly Linked List = 7->5->4->2

Do you want to continue (Type y or n)

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
4
Enter position
3

Singly Linked List = 7->5->2

Do you want to continue (Type y or n)

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
4
Enter position
1

Singly Linked List = 5->2

Do you want to continue (Type y or n)

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
4
Enter position
2

Singly Linked List = 5


Do you want to continue (Type y or n)

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
4
Enter position
1

Singly Linked List = empty

Do you want to continue (Type y or n)

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
5
Empty status = true

Singly Linked List = empty

Do you want to continue (Type y or n)

Potrebbero piacerti anche