Download as pdf or txt
Download as pdf or txt
You are on page 1of 155

EL

P
Data Structures and Algorithms Using Java
T
Debasis Samanta

N
Department of Computer Science & Engineering, IIT Kharagpur

Module 05: Linked List


Lecture 16 : Linked List Data Structure (Part-I)
EL
T
Ø About Linked List Structures

P
Ø Operation on Linked Lists

N
Ø Creating a list
Ø Insertion
Ø Deletion
Ø Traversals
EL
T
About Linked List Structures

N P
Concept of linked list

• A linked list is an ordered collection of finite, homogeneous data elements called

L
nodes where the linear order is maintained by means of links or pointers.

LINK

.
T E
P
Link to the next node
DATA

N
Array versus linked list

• Array

L
• Elements are stored in a contagious memory locations.

E
• Static data structure

• Linked List

P T
N
• Elements are not necessarily in contagious memory locations.
• Dynamic data structures
EL
T
Types of Linked List

N P
Different linked list structures

L
• Singly Linked List

• Doubly linked list

T E
P
• Circular linked list

N
EL
T
Single Linked List

P
N
Linked list using arrays
DATA LINK
41 38 50

L
42 -
HEADER 43 14 47

E
44 59 41
45 80
Header

T
46 -
59 38 64 47 72 45

P
N1 N2 N3 48
49

N
80 50 64 43
N6 . . .
. . .
72 . . .
14
N4 N5

Memory Array of
Location pointers
Dynamic linked list: Memory management
AVAIL

NEW

EL
P T
X
XY

HEADER X

N XY
Dynamic linked list: Memory management
AVAIL

HEADER

EL
P T
N
X
EL
T
Single Linked List Operations

P
N
Operations on single linked list

• Insertion of a node into a list

• Deletion of a node from a list

EL
T
• Copy a linked list to make a duplicate

P
N
• Merging two linked lists into a larger list

• Traversing
EL
T
Insertion Operations

P
N
Insertion of a node

Steps
• Get a new node from memory bank

EL
T
• Start from the header node

P
• Manage links to

N
• Insert at front

• Insert at end

• Insert at any position


Insertion of node at front

new

EL
T
From
memory

P
HEADER bank

N
X
X 1
Insertion of a node at end

L
new

T E
P
HEADER X

N
1

ptr
Insertion of a node at any position

new

EL
P T
HEADER

N
X

2
ptr 1

KEY X
EL
T
Deletion Operations

P
N
Deletion of a node from a linked list

Steps
• Start from the header node

EL
T
• Manage links to

P
• Delete at front

N
• Delete at end

• Delete at any position

• Return the deleted node to memory bank


Deletion of a node at front

L
HEADER

X
1

T E
P
ptr ptr1

KEY

N
X
Deletion of a node at end

L
HEADER
Return to the memory bank

T E
P
ptr1 ptr

N X
Deletion of a node at any position

HEADER

EL
T
ptr1 ptr

P
1

N
X KEY

Return to the memory bank


EL
T
Merge Operation

P
N
Single linked list: Merging

L
HEADER1

E
L1

T
...

L2

N P
HEADER2

X
To memory bank

...
EL
T
Circular Linked List

P
N
Circular linked list

HEADER

EL
PT
N
Merging two circular linked lists

EL
T
...
X

P
HEADER1

1
ptr1

N
ptr2
ptr2
2
HEADER2

X ...

Return to memory
EL
T
For details of linked list data

P
structures and applications

N
See the book
Classic Data Structures
Chapter 3
Prentice Hall of India
EL
PT
N
EL
P
Data Structures and Algorithms Using Java
T
Debasis Samanta

N
Department of Computer Science & Engineering, IIT Kharagpur

Module 05: Linked List


Lecture 17 : Linked List Data Structure (Part-II)
EL
T
Ø Types of Linked List

P
Ø Single linked list

N
Ø Double linked list
Ø Circular linked list

Ø Applications of Linked lists


EL
T
Types of Linked Lists

P
N
Different linked list structures

L
• Singly Linked List

E
• Circular linked list

T
• Doubly linked list

N P
EL
T
Double Linked List

N P
Double linked list

L
LLINK RLINK

E
DATA

P T
N
...
EL
T
Double Linked List: Insertion

N P
Insertion at front

NEW

EL
T
HEADE
 ‚ „ ƒ ptr

P
R

...

N
a) Insertion at the front
Insertion at end

L
HEADE

E
ptr
R

...

T
 ‚

P
b) Insertion at the end

N
NEW
Insertion at any position

EL ptr

P T
 „
‚ ƒ

N
NEW

c) Insertion at any intermediate position


EL
T
Double Linked List: Deletion

P
N
Delete at front

HEADE ptr

EL
T
ptr1
R 
X
...

P
X

‚
Return to the memory bank

N
a) Deletion at the front
Delete at end

Return to the memory bank

EL
T
HEADE ptr
ptr1
R


P
X
...

N
b) Deletion at the end
Delete from any position

HEADE
R
ptr1
ptr


EL ptr2

T
X KE

P
Y X

N
Return to the memory bank

c) Deletion at an intermediate position


EL
T
Applications of Linked List

N P
Applications of linked lists

• Sparse matrix manipulation

EL
T
• Polynomial manipulation

P
• Memory management

N
Sparse matrix

EL
T
i j ROWLINK

P
DATA

N COLLINK
Sparse matrix

L
Column
1 2 3 4 5

E
1 * * A * *

T
2 * X * * M

P
3 * * * * *

N
Row
4 P * * * O

5 * * L * *

6 K C * * B
Sparse matrix
HEADER

CH1 CH2 CH3 CH4 CH5


6 5 0 1 0 2

EL
1 0 1 3
RH1
A

T
2 5
2 0 2 2
RH2 M
X

P
3 0
RH3

N
4 5
4 0 4 1
RH4 O
P

5 5 3
0
RH5 L

6 0 6 1 6 2 6 5
RH6
K C B

Points to HEADER
Polynomial manipulation

P(x) = anxen + an–1xen–1 + · · · + a1xe1

C O E F F E XP O LIN K

EL
P T
N
3 8 -7 6 14 3 10 1 -5 0

P(x) = 3x8 – 7x6 + 14x3 + 10x – 5


Run-time memory management

EL
P T
N
Memory management: Allocation
AVAIL

NEW

EL
P T
X
XY

HEADER X

N XY
Memory management: Deallocation
AVAIL

HEADER

EL
P T
N
X
EL
T
For details of linked list data

P
structures and applications

N
See the book
Classic Data Structures
Chapter 3
Prentice Hall of India
EL
PT
N
EL
P
Data Structures and Algorithms Using Java
T
Debasis Samanta

N
Department of Computer Science & Engineering, IIT Kharagpur

Module 05: Linked List


Lecture 18 : Programming for Linked Lists (Part-I)
EL
T
Ø Defining a Linked List Structure

P
Ø Operations
Ø Traversal

N
Ø Insertion
Ø At front
Ø At end
Ø At any
Ø Merging
EL
T
Linked List in Java: Defining

P
N
Linked list data structure
• Like arrays, linked list is a linear data structure.

L
• Unlike arrays, linked list elements are not stored at the contiguous location, the
elements are linked using pointers as shown below.

T E
• How pointers in Java?
Hint:
N P
Linked list of a node can be represented as a class and a list itself
as another separate class. A class is used to create a reference object.
Programming overview

Class JLinkedList <T> {

Part-I: Field definition of the class

EL
P
Part-II: Methods definition of the class

T
}
N
Example 18.1: Creating a linked list structure
// This program shows how to define a (single) linked list

L
class JLinkedList<T> {
Node head; // head of list

E
class Node {
T data;

T
Node next;
// Constructor
Node (){

P
data = null;
next = null;
}

N
Node(T d){
data = d;
next = null;
}
}
JLinkedList(){ //LinkedList Header Node
head = new Node();
}
// Method to maintain the collection to be defined …
}
EL
T
Methods for Linked List

N P
Programming overview: Methods
• Methods
• Insertion operations

L
• Insertion at front

E
• Insertion at end
• Insertion at any position

T
• Traversal

P
• Printing the collection
• Reversing the ordering of elements

N
• Merging operation
• Merging two list into a single list

• Deletion operation
• Deletion from front
• Deletion from end
• Deletion from any position
Programming overview: Methods
• Methods
• Insertion operations

L
• Insertion at front public void insertFront(T data) { … }
• Insertion at end public void insertEnd(T data) { … }

E
• Insertion at any position public void insertKey(T data, T key) { … }

T
• Traversal
• Printing the collection public void printList() { … }

P
• Reversing the ordering of elements public void reverse() { … }

• Merging operation

N
• Merging two list into a single list public void merge(JLinkedList<T> ll){ … }

• Deletion operation
• Deletion from front public T deleteFront(T data) { … }
• Deletion from end public T deleteEnd(T data) { … }
• Deletion from any position public void deleteKey(T data, T key)
{ … }
EL
T
Insertion Operations

N P
Insertion operations: Overview
• Insertion operations
• Insertion at front

L
public void insertFront(T data) {

E

}

T
• Insertion at end
public void insertEnd(T data) {

P

}

N
• Insertion at any position
public void insertKey(T data, T key) {

}
Insertion operations: Insertion at FRONT

newNode

L
header
NULL

T E
P
temp

header

newNode

N
Example 18.2: Declaring a method to insert at FRONT

L
// This part of the program define a method to insert at front

E
import java.io.*;
import java.util.*;
// Java program to implement a Singly Linked List

T
public class JLinkedList<T> {
// Copy the code for the declaration of the class (see Slide #6)

P
// Defining the method to Insert at the front
public void insertFront(T data) {

N

}

} // End of JLinkedList class declaration

// Continued to next….
Example 18.2: Declaring a method to insert at FRONT

L
// Continued on ….

E
// Defining the method to Insert at the front
public void insertFront(T data){

T
// Create a new node with given data
Node newNode = new Node(data);

P
newNode.next = this.head.next;
// Make the new node as as the first node
this.head.next = newNode;

N
}

} // End of JLinkedList class declaration

// Continued to next….
Insertion operations: Insertion at END

newNode

L
header
NULL

T E
P
temp temp

N
header

newNode
Example 18.3: Declaring a method to insert at END

// Continued on ….

L
// This part of the program define a method to insert at end

E
import java.io.*;
import java.util.*;

T
// Java program to implement a Singly Linked List
public class JLinkedList<T> {

P
// Copy the code for the declaration of the class (see Slide #6)
// Defining the method to Insert at the front
public void insertEnd(T data) {

N

}

} // End of JLinkedList class declaration

// Continued to next….
Example 18.3: Declaring a method to insert at END

// Continued on….

L
// Defining the method to Insert at the end

E
public void insertEnd(T data){
Node newNode = new Node(data);

T
newNode.next = null;
Node temp = this.head;

P
while(temp.next != null) {
temp = temp.next;

N
}
temp.next = newNode;
}
} // End of JLinkedList class declaration

// Continued to next….
Insertion operations: Insertion at ANY (Key is not present)

header

L
NULL

T E
P
temp temp

N
header
Insertion operations: Insertion at ANY (Key is present)

header
temp temp

EL
T
key

P
newNode

N
Example 18.4: Declaring a method to insert at ANY

// Continued on ....

L
// This part of the program define a method to insert by key

E
import java.io.*;
import java.util.*;

T
// Java program to implement a Singly Linked List
public class JLinkedList<T> {

P
// Copy the code for the declaration of the class (see Slide #6)
// Defining the method to Insert at any position

N
public void insertKey(T data, T key) {

}

} // End of JLinkedList class declaration

// Continued to next….
Example 18.4: Declaring a method to insert at ANY
// Continued to next….

L
// Defining the method to insert at any position
public void insertKey(T data , T key) {
Node newNode = new Node(data);

E
newNode.next = null;
Node temp = this.head;

T
boolean status = false;
while(temp != null){
if(temp.data == key) {

P
status = true;
break;
}

N
temp = temp.next;
}
if(status) {
newNode.next = temp.next;
temp.next = newNode;
}
}
} // End of JLinkedList class declaration

// Continued to next….
EL
T
Traversal Operations

N P
Programming overview: Methods
• Methods
• Insertion operations

L
• Insertion at front public void insertFront(<T> data) { … }
• Insertion at end public void insertEnd(<T> data) { … }

E
• Insertion at any position public void insertKey(<T> key, <T> data) { … }

T
• Traversal
• Printing the collection public void printList() { … }

P
• Reversing the ordering of elements public void reverse() { … }

• Merging operation

N
• Merging two list into a single list public void merge(JLinkedList<T> ll){ … }

• Deletion operation
• Deletion from front public T deleteFront(T data) { … }
• Deletion from end public T deleteEnd(T data) { … }
• Deletion from any position public void insertKey(T data, T key)
{ … }
Travesral operations: Overview
• Traversal operations
• Printing the list

L
public void printList() {

E

}

T
• Reverse the ordering of elements
public JLinkedList<T> reverse(JLinkedList<T> ll) {

P

}

N
Traversal operation: Printing the list

temp

ELtemp

T
header
data

N P
Example 18.5: Declaring a method to print a list

// This part of the program define a method to insert at end

L
import java.io.*;

E
import java.util.*;

// Java program to implement a Singly Linked List

T
public class JLinkedList<T> {
// Copy the code for the declaration of the class (see Slide #6)

P
// Defining the method to print the list
public void printList( ) {

N

}

} // End of JLinkedList class declaration

// Continued to next….
Example 18.5: Defining a method to print a list

// Continued to next….

L
// Defining the method to print the list
public void printList(){

E
Node currNode = this.head.next;
System.out.print("LinkedList: ");

T
// Traverse through the LinkedList
while(currNode != null) {

P
// Print the data at current node
System.out.print(currNode.data + " ");
// Go to next node

N
currNode = currNode.next;
}
System.out.println();
}

} // End of JLinkedList class declaration

// Continued to next….
Example 18.6: Creating a single linked list, insertion and printing

L
// Continued on…
class LinkedListInsertionDemo {
public static void main(String args[]){

E
JLinkedList<Integer> list = new JLinkedList<Integer>();
list.insertEnd(9);
list.printList();

T
list.insertFront(5);
list.printList();

P
list.insertEnd(10);
list.printList();
list.insertKey(7,5);

N
list.printList();
list.insertKey(12,0);
list.printList();
list.insertKey(13,10);
list.printList();
list.insertFront(2);
list.printList();
}
}
EL
T
Linked List Merging

N P
Programming overview: Methods
• Methods
• Insertion operations

L
• Insertion at front public void insertFront(<T> data) { … }
• Insertion at end public void insertEnd(<T> data) { … }

E
• Insertion at any position public void insertKey(<T> key, <T> data) { … }

T
• Traversal
• Printing the collection public void printList() { … }

P
• Reversing the ordering of elements public void reverse() { … }

• Merging operation

N
• Merging two list into a single list public void merge(JLinkedList<T> ll){ … }

• Deletion operation
• Deletion from front public T deleteFront(<T> data) { … }
• Deletion from end public T deleteEnd(<T> data) { … }
• Deletion from any position public void insertKey(<T> key, <T> data)
{ … }
Traversal operations: Overview
• Merging operation
• Merging two lists into a single list

L
public void merge(JLinkedList<T> ll) {

E

}

P T
N
Merging operations

L
temp1 temp1

E
header

P
temp2

T
N
header
Example 18.7: Declaring a method to merge two lists

// This part of the program defines a method to insert at end

L
import java.io.*;

E
import java.util.*;
// Java program to implement a Singly Linked List

T
public class JLinkedList<T> {
// Copy the code for the declaration of the class (see Slide #6)

P
// Defining the method to merge two lists into a single list
public void merge(JLinkedList<T> ll ) {

N
}

} // End of JLinkedList class declaration

// Continued to next….
Example 18.7: Declaring a method to merge two lists

// Continued on ….

L
// Defining the method to merge two lists into a single list

E
public void merge(JLinkedList<T> l2) {
Node l1Node = this.head;
Node l2Node = l2.head;

T
while(l1Node.next != null ) {
l1Node = l1Node.next;

P
}
l1Node.next = l2Node.next;

N
free(l2.head); // Return the node to free memory
}
} // End of JLinkedList class declaration

// Continued to next….
Example 18.8: Creating a single linked list, insertion, merging and printing
// Continued on…

L
class LinkedListMergingDemo {
public static void main(String[] args){

E
JLinkedList<Integer> list1 = new LinkedList<Integer>();
LinkedList<Integer> list2 = new LinkedList<Integer>();
list1.insertFront(1);

T
list1.insertFront(2);
list1.insertEnd(3);

P
list1.insertEnd(4);
list1.printList();

N
list2.insertFront(5);
list2.insertEnd(6);
list2.printList();

// Merge the list list1 fter list2 and return the result as list 1
list1.merge(list2);
System.out.println("Merged List : ");
list1.printList();
}
} // End of the program
EL
P T
Ø Classic Data Structures, Debasis Samanta, 2nd Edition, Prentice Hall of India

N
Ø https://cse.iitkgp.ac.in/~dsamanta/javads/index.html
EL
PT
N
EL
P
Data Structures and Algorithms Using Java
T
Debasis Samanta

N
Department of Computer Science & Engineering, IIT Kharagpur

Module 05: Linked List


Lecture 19 : Programming for Linked Lists (Part-II)
Ø Single Linked List Operations

EL
Ø Deletion
Ø Deletion at front

P T
N
Ø Deletion at end
Ø Deletion at any position
Ø Traversal
Ø Double Linked List
Ø Reversing a single linked list Ø Programs for a double linked list
EL
T
Methods for Linked List

P
N
Programming overview: Methods
• Methods
• Insertion operations

L
• Insertion at front

E
• Insertion at end
• Insertion at any position

T
• Traversal

P
• Printing the collection
• Reversing the ordering of elements

N
• Merging operation
• Merging two list into a single list

• Deletion operation
• Deletion from front
• Deletion from end
• Deletion from any position
Programming overview: Methods
• Methods
• Insertion operations

L
• Insertion at front public void insertFront(T data) { … }

E
• Insertion at end public void insertEnd(T data) { … }
• Insertion at any position public void insertKey(T data, T key) { … }

T
• Traversal

P
• Printing the collection public void printList() { … }
• Reversing the ordering of elements public void reverse() { … }

N
• Merging operation
• Merging two list into a single list public void merge(JLinkedList<T> ll){ … }

• Deletion operation
• Deletion from front public T deleteFront() { … }
• Deletion from end public T deleteEnd() { … }
• Deletion from any position public void deleteKey(T key){ … }
EL
T
Deletion Operations

P
N
Deletion operations: Overview
• Deletion operations
• Deletion at front

L
public T deleteFront() {

E

}

T
• Deletion at end
public T deleteEnd() {

P

}

N
• Deletion at any position
public void deleteKey(T key) {

}
Deletion operations: Deletion at FRONT

L
header
NULL

T E
P
temp

N
header
Example 19.1: Declaring a method to delete from FRONT

// This part of the program define a method to insert at front

L
import java.io.*;

E
import java.util.*;
// Java program to implement a Singly Linked List

T
public class JLinkedList<T> {
// Copy the code for the declaration of the class (see Lecture-18, Slide #6)

P
// Defining the method to delete a node from the front
public T deleteFront() {

N
}

} // End of JLinkedList class declaration

// Continued to next….
Example 19.1: Declaring a method to delete from FRONT

// Continued on ….

L
// Defining the method to delete a node at the front

E
public T deleteFront() {
T x = null;

T
Node temp = this.head.next, prev = null;
if(temp != null) {

P
x = temp.data;
this.head.next = temp.next; // Changed head
// Display the message

N
System.out.println("Element deleted");
}
return x; // Return the deleted data
}
} // End of JLinkedList class declaration

// Continued to next….
Deletion operations: Overview
• Deletion operations
• Deletion at front

L
public T deleteFront() {

E

}

T
• Deletion at end
public T deleteEnd() {

P

}

N
• Deletion at any position
public void deleteKey(T key) {

}
Deletion operations: Deletion at END

L
header
NULL

T E
P
temp prev temp

header

N
Example 19.2: Declaring a method to delete from END

// This part of the program define a method to insert at front

L
import java.io.*;

E
import java.util.*;
// Java program to implement a Singly Linked List

T
public class JLinkedList<T> {
// Copy the code for the declaration of the class (see Lecture-18, Slide #6)

P
// Defining the method to delete a node from the rear
public T deleteEnd() {

N
}

} // End of JLinkedList class declaration

// Continued to next….
Example 19.2: Declaring a method to delete from END

// Continued on ….

L
// Defining the method to delete a node from the end
public T deleteEnd () {

E
T x = null;
Node temp = this.head.next, prev = null;

T
if (temp != null) { // If the list is not empty
while(temp != null) { // Move to the end node
prev = temp;

P
temp = temp.next;
}
x = temp.data;

N
prev.next = null;
}
return x;
}
} // End of JLinkedList class declaration

// Continued to next…. Null)


Deletion operations: Overview
• Deletion operations
• Deletion at front

L
public T deleteFront() {

E

}

T
• Deletion at end
public T deleteEnd() {

P

}

N
• Deletion at any position
public void deleteKey(T key) {

}
Deletion operations: Deletion at ANY
header
NULL
List is empty

EL
T
temp temp

header Key is not present

header
prev

N P
temp

key
Key is present
Example 19.3: Declaring a method to delete at ANY

// This part of the program define a method to insert at front

L
import java.io.*;

E
import java.util.*;
// Java program to implement a Singly Linked List
public class JLinkedList<T> {

T
// Copy the code for the declaration of the class (see Lecture-18, Slide #6)
// Defining the method to delete a node by the presence of a key

P
public void deleteKey(T key) {

N
}

} // End of JLinkedList class declaration

// Continued to next….
Example 19.3: Declaring a method to delete from ANY

L
// Continued on ….

// Defining the method to delete a node from any position

E
public void deleteKey(T key){
Node temp = this.head.next, prev = null;
while(temp != null) {

T
if(temp.data == key) {
prev.next = temp.next;

P
// Display the message
System.out.println(key+ " position element deleted");
break;

N
}
else {
prev = temp;
temp = temp.next;
}
}

}
} // End of JLinkedList class declaration
// Continued to next….
Example 19.4: Linked list with insertion, and deletion operations
// Continued on ….

class LinkedListDeletionDemo {

L
public static void main(String[] args) {
JLinkedList<Integer> list = new JLinkedList<Integer>();
list.insertFront(1);

E
list.insertFront(2);
list.insertFront(3);
list.insertFront(4);

T
list.insertFront(5);
list.insertFront(6);
list.insertFront(7);

P
list.insertFront(8);
// Print the LinkedList
list.printList();

N
list.deleteKey(1);
list.printList();

list.deleteFront( );
list.printList();

list.deleteEnd();
list.printList();
}
}
Programming overview: Methods
• Methods
• Insertion operations

L
• Insertion at front public void insertFront(<T> data) { … }

E
• Insertion at end public void insertEnd(<T> data) { … }
• Insertion at any position public void insertKey(<T> key, <T> data) { … }

T
• Traversal

P
• Printing the collection public void printList() { … }
• Reversing the ordering of elements public void reverse() { … }

N
• Merging operation
• Merging two list into a single list public void merge(JLinkedList<T> ll){ … }

• Deletion operation
• Deletion from front public T deleteFront() { … }
• Deletion from end public T deleteEnd() { … }
• Deletion from any position public void deleteKey(T key){ … }
EL
T
Linked List Reversal

N P
Reversing a single linked list a list

EL
P T
N
Example 19.5: Declaring a method to reveres a list

L
// This part of the program define a method to insert at front

E
import java.io.*;
import java.util.*;
// Java program to implement a Singly Linked List

T
public class JLinkedList<T> {
// Copy the code for the declaration of the class (see Lecture-18, Slide #6)

P
// Defining the method to reverse the ordering of the elements
public void reverse( ) {

N
}

} // End of JLinkedList class declaration

// Continued to next….
Example 19.5: Defining a method to reverse a list
// Continued on ….

// Defining the method to reverse the ordering of nodes method

L
public Node remove(Node n) {
Node current = n;
Node next = n.next;

E
Node prev = null;

while (current != null) {

T
next = current.next;
current.next = prev;

P
prev = current;
current = next;
}

N
this.head.next = prev;
return next;
}

public void reverse() {


Node currNode = this.head.next;
System.out.print("Reversed List : ");
remove(currNode);
}

} // End of the class JLinkedList


// Continued to next….
Example 19.6: Creation of a list and reversal
// Continued on ….

class LinkeListReversalDemo{
public static void main(String args[]) {

L
JLinkedList<Integer> list = new JLinkedList<Integer>();

E
list.insertEnd(9);
list.printList();
list.insertFront(5);

T
list.printList();
list.insertEnd(10);
list.printList();

P
list.insertKey(7,5);
list.printList();
list.insertKey(12,0);

N
list.printList();
list.insertKey(13,10);
list.printList();
list.insertFront(2);
list.printList();

list.reverse();
list.printList();
}
}
EL
T
Double Linked Lists

P
N
Programming with double linked list

L
LLINK RLINK

E
DATA

P T
N
...
EL
P T
Ø Classic Data Structures, Debasis Samanta, 2nd Edition, Prentice Hall of India

N
Ø https://cse.iitkgp.ac.in/~dsamanta/javads/index.html
EL
PT
N
EL
P T
Data Structures and Algorithms Using Java
Debasis Samanta

N
Department of Computer Science & Engineering, IIT Kharagpur

Module 05: Linked List


Lecture 20 : Linked Lists Using JCF
EL
T
Ø Class LinkedList in JCF

P
Ø Defining Linked List
Ø Creation of Linked List

N
Ø Operations
Ø Insertion
Ø Deletion
Ø Traversals
Linked List Class

• The LinkedList class is a member in the Java Collections Framework to support


sequential access of a list of items unlike ArrayList, which provides indexed

L
access.

E
• It inherits the AbstractSequentialList class and implements the List and Deque
interfaces.

T
Collection

List

AbstractSequentialList

N P
LinkedList
Queue

Dequeue

The class implementation hierarchy of LinkedList class


Features of linked list class

L
Following are the few salient features of this collection:

E
• It provides a linked-list data structure

T
• The class can contain duplicate elements.
• The class uses a doubly linked list to store the elements.

P
• The class maintains insertion order.
• The class is non-synchronized.

N
• Manipulation is faster than array because no shifting is required.
• The LinkedList class can be used to maintain a collection as a linked list, stack or queue.
EL
T
Creating Linked List

N P
Constructors in the LinkedList class

L
• The LinkedList class consists of two constructors, which are as follows:

Constructor

T E Description
It is used to create an empty list.

P
LinkedList()

LinkedList(Collection<? extends E> c) It is used to construct a list containing the elements of the

N
specified collection. The ordering of the element in the list
and collection is same.
Example 20.1: Create a linked list
// This program define a linked list and add some items into it

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

E
// Creating an empty ll of class LinkedList
LinkedList<String>ll = new LinkedList<String>();

T
// Adding elements to the linked list using a number of add methods
ll.add("Mumbai");
ll.add("Chennai");

P
ll.add("Kolkata");
ll.add("Delhi");
ll.add("Bangalore");

N
ll.add("Guwahati");
ll.add("Hyderabad");
// System.out.println("Linked list : "+ ll); // Simple printing
// Printing the list using an iterator
Iterator<String>itr=ll.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Example 20.2: Create a linked list with user defined objects

/* This program shows how to create an array of objects of type Students and then add the array

L
into a linked list and then printing the same. */

import java.util.*;

E
//Declaration of a user defined class
class Student {

T
String name;
double marks;

P
// Constructor
Student(String s, double m) {
name = s;

N
marks = m;
}
void printData () {// To parant a reacord
System.out.print("Name : " + name);
System.out.println(" Marks : " + marks);
}
}
// Continued to next …
Example 20.2: Create a linked list with user defined objects

// Continued on…

L
// The main class is defined below.

E
public class CreateLLofCollection {
public static void main(String args[]) {

T
// Create an aaray of objects
Student sArray[] = new Student[5]; // To store 5 objects

P
// Create the array sArray

N
sArray[0] = new Student("Ram", 79.6);
sArray[1] = new Student("Rahim", 85.5);
sArray[2] = new Student("John", 90.1);
sArray[3] = new Student("Lisa", 69.4);
sArray[4] = new Student("Ana", 59.8);

// Continued to next …
Example 20.2: Create a linked list with user defined objects

L
// Continued on…

// Creating a linked-list with sArray collection

E
LinkedList<Student> ll = new LinkedList<Student>(Arrays.asList(sArray));

T
Student temp;
// Printing the list using an iterator

P
Iterator<Student>itr=ll.iterator();
while(itr.hasNext()){
temp = itr.next();

N
temp.printData(); // Print the current record.
}
}
}
EL
T
Operations with LinkedList

P
N
Operations with LinkedList collection

EL
• The following operations with LinkedList are usually frequently.

T
• Creating a linked-list

P
• Insertion of an item in a linked-list
• Deletion of an item from a linked-list

N
• Traversing a linked-list
EL
T
Insertion into LinkedList

P
N
Insertion: Methods in the LinkedList class

Method Description

L
boolean add(E e) It is used to append the specified element to the end of a list.

E
void add(int index, E It is used to insert the specified element at the specified position index in
element) a list.

T
boolean addAll(Collection<? It is used to append all of the elements in the specified collection to the
extends E> c) end of this list, in the order that they are returned by the specified

P
collection's iterator.
boolean addAll(int index, It is used to append all the elements in the specified collection, starting

N
Collection<? extends E> c) at the specified position of the list.
void addFirst(E e) It is used to insert the given element at the beginning of a list.
void addLast(E e) It is used to append the given element to the end of a list.
Example 20.3: Insertion at different locations
/*This program shows how items can be inserted at different locations in a linked list. For
this purpose, there are methods like add(), addFirst(), addLast() are defined in the LinkedList

L
class. */

import java.util.*;

E
public class LLinsertionDemo {

T
public static void main(String args[]) {
// Creating an empty ll of class LinkedList

P
LinkedList<String>ll = new LinkedList<String>();
// Adding elements to the linked list using a number of add methods
ll.add("Mumbai"); // Add an initial item

N
ll.add("Chennai"); // Add another item
ll.addLast("Kolkata"); // Add at the end
ll.addFirst("Delhi"); // Add at the front
ll.add(2, "Bangalore"); // Add in the specific location
ll.add("Guwahati"); // Sequential add goes at the end
ll.add("Hyderabad"); // Another sequential insertion

// Continued to next …
Example 20.3: Insertion at different locations

L
// Continued to next …

// Printing the list using an iterator

E
Iterator<String>itr=ll.iterator();
while(itr.hasNext()){

T
System.out.println(itr.next());
}

P
// Alternatively:
System.out.println("Linked list : "+ ll); // Simple printing
}

N
}
Example 20.4: Insertion of a list into a LinkedList
/* A sub list can be inserted into a linked list in addition to a single item. This program
shows how a sub list can be inserted at different locations in a linked list. For this

L
purpose, the addAll() method is used.*/

import java.util.*;

E
public class InsertSubListToLL{

T
public static void main(String args[]){
LinkedList<String> ll1 = new LinkedList<String>();

P
System.out.println("Initial list of elements: "+ ll1);
ll1.add("MP Allahabad");
ll1.add("MP Lucknow");

N
ll1.add("MP Varanasi");
System.out.println("Initial list: ” + ll1);

// Create another linked list, say ll2


LinkedList<String> ll2 = new LinkedList<String>();
ll2.add("MLA Nadia");
ll2.add("MLA Kharagpur");

// Continued to next …
Example 20.4: Insertion of a list into a LinkedList
// Continued on …

L
//Adding the second list (ll2) to the first list (ll1)
ll1.addAll(ll2);

E
System.out.println("After adding ll2 to ll1: ” + ll1);

// Create another linked list, say ll3

T
LinkedList<String> ll3 = new LinkedList<String>();
ll3.add("MLA Durgapur");

P
ll3.add("MLA Howrah");

N
//Inserrt ll3 at a specific position of ll1
ll1.addAll(3, ll3); // Insert ll3 at location 3 of ll1
System.out.println("After insetting ll3: ” + ll1);
//Do some normal insertions
ll1.addFirst("President");
ll1.addLast("Prime Minister");
ll1.add("MP Chennai");
System.out.println("The final list ” + ll1);
}
}
EL
T
Deletion from LinkedList

P
N
Deletion: Methods in the LinkedList class

L
Method Description
E poll() It retrieves and removes the first element of a list.

E
E pollFirst() It retrieves and removes the first element of a list, or returns null if a list is
empty.

T
E pollLast() It retrieves and removes the last element of a list, or returns null if a list is
empty.

P
E pop() It pops an element from the stack represented by a list.
void push(E e) It pushes an element onto the stack represented by a list.

N
E remove() It is used to retrieve and removes the first element of a list.
E remove(int index) It is used to remove the element at the specified position in a list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element in a list.

Continued to next…
Methods in the LinkedList Class

Continued from previous…

L
Method Description
E removeFirst() It removes and returns the first element from a list.

E
boolean removeFirstOccurrence(Object o) It is used to remove the first occurrence of the specified element
in a list (when traversing the list from head to tail).

T
E removeLast() It removes and returns the last element from a list.

P
boolean removeLastOccurrence(Object o) It removes the last occurrence of the specified element in a list
(when traversing the list from head to tail).

N
void clear() It is used to remove all the elements from a list.
Example 20.5: Deletion of an object from a LinkedList

L
/* Like insertion, deletion operation on a linked list can be carried our many ways.
Following few examples illustrates the deletion operation with methods remove(),
removeFirst(), removeLast(), etc.*/

E
import java.util.*;

T
public class DeletionFromLL {
public static void main(String [] args) {

P
// Creating a linked list
LinkedList<String>ll1 = new LinkedList<String>();

N
ll1.add("A");
ll1.add("E");
ll1.add("I");
ll1.add("O");
ll1.add("U");
ll1.add("H");
System.out.println("List of vowels: "+ll1);

// Continued to next …
Example 20.5: Deletion of an object from a LinkedList

// Continued on …

L
//Removing specific element from the linked list
ll1.remove("H"); // Rmovee the vowel H

E
System.out.println("After deletion of H : "+ll1);

//Removing element on the basis of specific position

T
ll1.remove(0); // This will remove A from the list
System.out.println("After invoking remove(index) method: "+ll1);

P
// Let’s create another list of semi-vowels
LinkedList<String> ll2=new LinkedList<String>();

N
ll2.add("M");
ll2.add("N");
// Adding new elements to the list of vowels
ll1.addAll(ll2); // Append ll2 after ll1
System.out.println("Updated list : "+ll1);

//Removing first element from the list


ll1.removeFirst();
System.out.println("After invoking removeFirst() method: "+ll1);

// Continued to next …
Example 20.5: Deletion of an object from a LinkedList

// Continued on …

L
//Removing last element from the list
ll1.removeLast();
System.out.println("After invoking removeLast() method: "+ll1);

E
// Removing all elements from ll2
ll1.removeAll(ll2);
System.out.println("After removing semi-vowels: "+ll1);

T
ll1.add("A");
ll1.add("B");

P
ll1.add("A");
//Removing first occurrence of element from the list
ll1.removeFirstOccurrence("A");

N
System.out.println("After removing first occurrence of A: "+ll1);
//Removing the last occurrence of B
ll1.removeLastOccurrence("B");
System.out.println("After invoking removeLastOccurrence() method: "+ll1);
//Removing all the elements available in the list
ll1.clear();
System.out.println("After invoking clear() method: "+ll1);
}
}
EL
T
Traversals of a LinkedList

P
N
Example 20.6: Traversal operation on a linked List collection
We have learned how to print a linked-list in sequential order starting from the first item in the list. The
LinkedList class allow you to traverse a linked in reverse order as well. For this purpose, you should use the

L
method descendingIterator(). This can be applied to a list storing of any type of items.

E
/* The following program illustrates how to traverse two different type of lists in
reverse order, that is, from the end to the front. */

T
import java.util.*;

P
public class TravserseReverseLL{
public static void main(String args[]){
// Case 1: a linked list of countries

N
LinkedList<String> lCountries = new LinkedList<String>();
lCountries.add("Australia");
lCountries.add("India");
lCountries.add("South Africa");
lCountries.add("Zimbabwe");

// Continued to next …
Example 20.6: Traversal operation on a linked List collection
// Continued on…

L
//Traversing the list of countries in reverse order
Iterator itr1 =lCountries.descendingIterator();
while(itr1.hasNext()) {

E
System.out.println(itr1.next());
}

T
// Case 2: a linked list of numbers

P
LinkedList<Integer> lNumbers = new LinkedList<Integer>();
lNumbers.add(123);
lNumbers.add(345);

N
lNumbers.add(567);
lNumbers.add(789);

//Traversing the list of numbers in reverse order


Iterator itr2 = lNumbers.descendingIterator();
while(itr2.hasNext()) {
System.out.println(itr2.next());
}
}
}
EL
T
Miscellaneous Operations

P
N
Example 20.7: Miscellaneous operations
/* The LinkedList class is loaded with several other methods like get(), contain(),
size(), set(), etc. The following program illustrates those methods and their utilities

L
in Java programming. */

import java.util.*;

E
public class OtherMethodsOfLL{
public static void main(String args[]){// Creating a linked list

T
LinkedList<String>lLetters = new LinkedList<String>();
lLetters.add("J");

P
lLetters.add("O");
lLetters.add("Y");
lLetters.add("W");

N
lLetters.add("I");
lLetters.add("T");
lLetters.add("H");
lLetters.add("J");
lLetters.add("A");
lLetters.add("V");
lLetters.add("A");

// Continued to next …
Example 20.7: Miscellaneous operations
// Continued on …

lLetters.add("2020");

L
System.out.println("List : "+lLetters);
// Finding an elements in the linked list

E
boolean status = lLetters.contains("Z");
if(status)

T
System.out.println("List contains the element 'Z' ");
else

P
System.out.println("List doesn't contain 'Z'");

// Finding the number of elements in the linked list

N
int size = lLetters.size();
System.out.println("Number of letters = "+ size);
// Get and set elements from the linked list
String element = lLetters.get(11);
System.out.println("Element returned by get() : ” + element);
lLetters.set(11, "The fun");
System.out.println("Linked list after change : ” + lLetters);
}
}
Example 20.8: Case study with a user defined objects
/* The following, a program shows a list a number of books, insertion of another books
in the list, deletion of books and then traversing of the books, etc.*/

L
import java.util.*;

E
// Defining a calls Book
class Book {

T
int accnNo;
String title, author, publisher;

P
double cost;
// Constructor of the class
Book(int id, String t, String auth, String pub, double val) {

N
accnNo = id;
title = t;
author = auth;
publisher = pub;
cost = val;
}
}

// Continued to next …
Example 20.8: Case Study with a user defined objects
// Continued on …

// The main class maintaining a library of books

L
public class LibraryLL {
public static void main(String[] args) {

E
List<Book> library =new LinkedList<Book>(); //Creating list of Books
//Creating a list of Books

T
Book b1 = new Book(101,"Oracle Java","Leslie Lamport","Oxford",88.5);
Book b2 = new Book(102,"Complete Java","McGraw Hill", "TMH" , 94);

P
Book b3 = new Book(103,"Joy with Java","Samanta","Prentice Hall",69.6);
library.add(b1); //Adding Books to list
library.add(b2);

N
library.add(b3);

//Traversing the list


for(Book b:library){System.out.println("Book ID: " +b.accnNo);
System.out.print(b.title+" "+b.author+" "+b.publisher+" "+b.cost);
System.out.println();
}
}
}
EL
P T
Ø https://cse.iitkgp.ac.in/~dsamanta/javads/index.html

N
Ø https://docs.oracle.com/javase/tutorial/
EL
PT
N

You might also like