Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Linked List (insertion, deletion, doubly linked list)

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

Linked List (insertion, deletion, doubly linked list)

Linked List
 Like arrays, Linked List is a linear data structure.
Unlike arrays, linked list elements are not stored at a
contiguous location; the elements are linked using
pointers.
Why Linked List?
 Arrays can be used to store linear data of similar types,
but arrays have the following limitations.
1) The size of the arrays is fixed: So we must know the
upper limit on the number of elements in advance.
Also, generally, the allocated memory is equal to the
upper limit irrespective of the usage.
2) Inserting a new element in an array of elements is
expensive because the room has to be created for the
new elements and to create room existing elements
have to be shifted.
Advantages & Drawbacks
 Advantages over arrays
1) Dynamic size
2) Ease of insertion/deletion
 Drawbacks:
1) Random access is not allowed. We have to access
elements sequentially starting from the first node. So
we cannot do binary search with linked lists efficiently
with its default implementation. Read about it here.
2) Extra memory space for a pointer is required with
each element of the list.
Representation
 LinkedList can be represented as a class and a Node as
a separate class. The LinkedList class contains a
reference of Node class type.
class LinkedList {
Node head; // head of the list

/* Linked list Node*/


static class Node {
int data;
Node next;

// Constructor to create a new node


// Next is by default initialized
// as null
Node(int d) { data = d; }
}
}
Ex 01
class LinkedList {
Node head; // head of list
/* Linked list Node. This inner class is made static so that
main() can access it */
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
} // Constructor
}
/* This function prints contents of linked list starting from head */
public void printList() {
Node n = head;
while (n != null) {
System.out.print(n.data + " ");
n = n.next;
}
}
Ex 01

/* method to create a simple linked list with 3 nodes*/


public static void main(String[] args) {
/* Start with the empty list. */
LinkedList llist = new LinkedList();
llist.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
llist.head.next = second; // Link first node with the second node
second.next = third; // Link first node with the second node
llist.printList();
}
}

Output:
1 2 3
Node insertion
 A node can be added in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list.
Add a node at the front:
 The new node is always added before the head of the
given Linked List. And newly added node becomes the
new head of the Linked List. For example if the given
Linked List is 10->15->20->25 and we add an item 5 at
the front, then the Linked List becomes 5->10->15-
>20->25. Let us call the function that adds at the front
of the list is push(). The push() must receive a pointer
to the head pointer, because push must change the
head pointer to point to the new node
Add node at the front
 Following are the 4 steps to add node at the front:

/* This function is in LinkedList class. Inserts a


new Node at front of the list. This method is
defined inside LinkedList class shown above */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);

/* 3. Make next of new Node as head */


new_node.next = head;

/* 4. Move the head to point to new Node */


head = new_node;
}
Add a node after a given node: (5 steps process)
 We are given pointer to a node, and the new node is
inserted after the given node.
1. If prev_node == null : means list is empty, display error!
2. Allocate the Node &
3. Put in the data

5 4
/* This function is in LinkedList class.
Inserts a new node after the given prev_node. This method is
defined inside LinkedList class shown above */
public void insertAfter(Node prev_node, int new_data)
{
/* 1. Check if the given Node is null */
if (prev_node == null)
{
System.out.println("The given previous node cannot be null");
return;
}
/* 2. Allocate the Node &
3. Put in the data*/
Node new_node = new Node(new_data);

/* 4. Make next of new Node as next of prev_node */


new_node.next = prev_node.next;

/* 5. make next of prev_node as new_node */


prev_node.next = new_node;
}
Add a node at the end: (6 steps process)
 The new node is always added after the last node of the
given Linked List. E.g., if the given Linked List is 5->10->15-
>20->25 and we add an item 30 at the end, then the Linked
List becomes 5->10->15->20->25->30.
Since a Linked List is typically represented by the head of
it, we have to traverse the list till end and then change the
next of last node to new node.
5 -> -> ->

1. Allocate the Node &


2. Put in the data 1,2
3. If the Linked List is empty, then make the new node as head
4. This new node is going to be the last node, so make next of it as null
5. traverse till the last node
6. Change the next of last node
/* Appends a new node at the end. This method is
defined inside LinkedList class shown above */
public void append(int new_data) {
/* 1. Allocate the Node &
2. Put in the data
Node new_node = new Node(new_data);
/* 3. If the Linked List is empty, then make the
new node as head */
if (head == null) {
head = new Node(new_data);
return;
}
/* 4. This new node is going to be the last node, so
make next of it as null */
new_node.next = null;
/* 5. traverse till the last node */
Node last = head;
while (last.next != null)
last = last.next;

/* 6. Change the next of last node */


last.next = new_node;
return;
}
Ex02: append, push & insertAfter methods
/* Driver program to test above functions. Ideally this function should
be in a separate user class. It is kept here to keep code compact */
public static void main(String[] args) {
/* Start with the empty list */
LinkedList llist = new LinkedList();
// Insert 6. So linked list becomes 6->NUllist
llist.append(6);
// Insert 7 at the beginning. So linked list becomes
// 7->6->NUllist
llist.push(7);
// Insert 1 at the beginning. So linked list becomes
// 1->7->6->NUllist
llist.push(1);
// Insert 4 at the end. So linked list becomes Output:
// 1->7->6->4->NUllist Created Linked list is:
llist.append(4); 1 7 8 6 4
// Insert 8, after 7. So linked list becomes Created Linked list is:
// 1->7->8->6->4->NUllist 1 7 8 6 5 4
llist.insertAfter(llist.head.next, 8);
System.out.println("\nCreated Linked list is: ");
llist.printList();
llist.insertAfter(llist.head.next.next.next, 5);
System.out.println("\nCreated Linked list is: ");
llist.printList();
Deleting a node
 Given a ‘key’, delete the first occurrence of this key in
linked list.
To delete a node from linked list, we need to do
following steps.
1) Find previous node of the node to be deleted.
2) Change the next of previous node.
3) Free memory for the node to be deleted.
3
1

2
// ex03: Java program to demonstrate deletion in singly linked list
class LinkedList {
Node head; // head of list
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
/* Given a key, deletes the first occurrence of key in linked list */
void deleteNode(int key) {
Node temp = head, prev = null; // Store head node
// If head node itself holds the key to be deleted
if (temp != null && temp.data == key) {
head = temp.next; // Changed head
return;
}
// Search for the key to be deleted, keep track of the
// previous node as we need to change temp.next
while (temp != null && temp.data != key) {
prev = temp;
temp = temp.next;
}
if (temp == null) return; // If key was not present in linked list
prev.next = temp.next; // Unlink the node from linked list
}
Ex03: Deleting a node
/* Inserts a new Node at front of the list. */
public void push(int new_data) {
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
/* This function prints contents of linked list starting from
the given node */
public void printList() { Output:
Node tnode = head; Created Linked list is:
while (tnode != null) { 2 3 1 7
System.out.print(tnode.data+" ");
tnode = tnode.next;
Linked List after Deletion at position 4:
} 2 3 7
}
public static void main(String[] args) {
LinkedList llist = new LinkedList();
llist.push(7);
llist.push(1);
llist.push(3);
llist.push(2);
System.out.println("\nCreated Linked list is:");
llist.printList();
llist.deleteNode(1); // Delete node at position 4
System.out.println("\nLinked List after Deletion at position 4:");
llist.printList();
}
}
Delete node at a given position
 Delete a Linked List node at a given position
 Given a singly linked list and a position, delete a linked
list node at the given position.
 Example:
Input: position = 1, Linked List = 8->2->3->1->7
Output: Linked List = 8->3->1->7

Input: position = 0, Linked List = 8->2->3->1->7


Output: Linked List = 2->3->1->7

Hint: If node to be deleted is root, simply delete it. To delete a middle node,
we must have pointer to the node previous to the node to be deleted. So if
positions is not zero, we run a loop position-1 times and get pointer to the
previous node.
Ex04
/* Given a reference (pointer to pointer) to the head of a list
and a position, deletes the node at the given position */
void deleteNodeAt(int position) {
// If linked list is empty
if (head == null)
return;
// Store head node
Node temp = head;
// If head needs to be removed
if (position == 0) {
head = temp.next; // Change head
return;
}
// Find previous node of the node to be deleted
for (int i=0; temp!=null && i<position-1; i++)
temp = temp.next;
// If position is more than number of ndoes
if (temp == null || temp.next == null)
return;
// Node temp->next is the node to be deleted
// Store pointer to the next of node to be deleted
Node next = temp.next.next;
temp.next = next; // Unlink the deleted node from list
}
Ex04 Output:
Created Linked list is:
3 1 3 1 7
public static void main(String[] args) {
Linked List after Deletion at
LinkedList llist = new LinkedList();
position 4:
llist.push(7);
3 3 1 7
llist.push(1);
Linked List after Deletion at
llist.push(3);
position 4:
llist.push(1);
3 3 7
llist.push(3);
System.out.println("\nCreated Linked list is:");
llist.printList(); //3 1 3 1 7
llist.deleteNode(1); //Delete first occurance of 1 - i.e., at position 1
System.out.println("\nLinked List after Deletion at position 4:");
llist.printList(); //3 3 1 7
llist.deleteNodeAt(2); //Delete node at position 2
System.out.println("\nLinked List after Deletion at position 4:");
llist.printList(); //3 3 7
}
Doubly Linked List
 A Doubly Linked List (DLL) contains an extra pointer,
typically called previous pointer, together with next
pointer and data
Advantages over singly linked list

1) A DLL can be traversed in both forward and
backward direction.
2) The delete operation in DLL is more efficient if
pointer to the node to be deleted is given.
3) We can quickly insert a new node before a given
node.
Disadvantages over singly linked list
 1) Every node of DLL Require extra space for an
previous pointer.
2) All operations require an extra pointer previous to
be maintained. For example, in insertion, we need to
modify previous pointers together with next pointers.
For example in following functions for insertions at
different positions, we need 1 or 2 extra steps to set
previous pointer.
Add a node at the front:
Add a node after a given node:
Add a node at the end
Add a node before a given node
Lab task 1
 T1: Provided Practice code for lab:
 Ex05: DLL.java - Doubly Linked List operations
 Ex06: DeleteDLL.java - Deletes a DLL node at a given
position
 Ex07: RotateDLL.java - Rotate Doubly linked list by N
nodes
Lab 10 task:
 Write code for pairwise swap elements of linked list
Given a singly linked list, write a function to swap
elements pairwise.
 Example - for singly linked list:
Input : 8->9->10->11->12->13->NULL
Output : 9->8->11->10->13->12->NULL
 Input : 1->2->3->4->5->NULL
Output : 2->1->4->3->5->NULL
Lab tasks
 T2: Print the middle of a given linked list
 T3: Find Length of a Linked List (Iterative and Recursive)
 T4: Search an element in a Linked List
 T5: Reverse a linked list
 Implement all above Tasks in java for:
 Singly Linked List
 Doubly Linked List
 Do not use any built-in classes / libraries.
 If plagiarism detected, you will get zero marks.
 I would really appreciate if you submit the lab task
within lab timings. (i.e., before 9pm today)
 Last date of submission is 4th November 2024 – 11:55
PM.

You might also like