Linked List Notes

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

C.B.

PATEL COMPUTER COLLEGE Data Structure

Unit 5. Data Structure Implementation and Applet Classes

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 but in Linked list if we have the head node then we can traverse to
any node through it and insert new node at the required position.

For example, in a system, if we maintain a sorted list of IDs in an array id[].


id[] = [1000, 1010, 1050, 2000, 2040].

And if we want to insert a new ID 1005, then to maintain the sorted order, we have
to move all the elements after 1000 (excluding 1000).

Page 1
C.B. PATEL COMPUTER COLLEGE Data Structure

Deletion is also expensive with arrays until unless some special techniques are
used. For example, to delete 1010 in id[], everything after 1010 has to be moved
due to this so much work is being done which affects the efficiency of the code.

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(head 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.

3) Not cache friendly. Since array elements are contiguous locations, there is
locality of reference which is not there in case of linked lists.

Representation:

A linked list is represented by a pointer to the first node of the linked list. The first
node is called the head. If the linked list is empty, then the value of the head points
to NULL.

Each node in a list consists of at least two parts:

1) data (we can store integer, strings or any type of data).

Page 2
C.B. PATEL COMPUTER COLLEGE Data Structure

2) Pointer (Or Reference) to the next node (connects one node to another)
In C, we can represent a node using structures. Below is an example of a linked list
node with integer data.

In Java , LinkedList can be represented as a class and a Node as a separate class.


The LinkedList class contains a reference of Node class type.

Create and Display a singly linked list

The singly linked list is a linear data structure in which each element of the list
contains a pointer which points to the next element in the list. Each element in the
singly linked list is called a node. Each node has two components: data and a pointer
next which points to the next node in the list. The first node of the list is called as
head, and the last node of the list is called a tail. The last node of the list contains a
pointer to the null. Each node in the list can be accessed linearly by traversing
through the list from head to tail.

Consider the above example; node 1 is the head of the list and node 4 is the tail of
the list. Each node is connected in such a way that node 1 is pointing to node 2 which
in turn pointing to node 3. Node 3 is again pointing to node 4. Node 4 is pointing to
null as it is the last node of the list.

Insert a new node at the middle of the singly linked list

In this program, we will create a singly linked list and add a new node at the middle
of the list. To accomplish this task, we will calculate the size of the list and divide it
by 2 to get the mid-point of the list where the new node needs to be inserted.

Page 3
C.B. PATEL COMPUTER COLLEGE Data Structure

Consider the above diagram; node 1 represents the head of the original list. Let node
New is the new node which needs to be added at the middle of the list. First, we
calculate size which in this case is 4. So, to get the mid-point, we divide it by 2 and
store it in a variable count. Node current will point to head. First, we iterate through
the list till current points to the mid position. Define another node temp which point
to node next to current. Insert the New node between current and temp

Insert a new node at the beginning of the singly linked list

In this program, we will create a singly linked list and add a new node at the
beginning of the list. To accomplish this task, we will store head to a temporary node
temp. Make newly added node as the new head of the list. Then, add temp (old head)
after new head.

Page 4
C.B. PATEL COMPUTER COLLEGE Data Structure

Consider the above list; node 1 represents the head of the original list. Let node New
be the new node which needs to be added at the beginning of the list. Node temp will
point to head, i.e., 1. Make New as the new head of the list and add temp after new
head such that node next to New will be 1.

Insert a new node at the end of the singly linked list

In this program, we will create a singly linked list and add a new node at the end of
the list. To accomplish this task, add a new node after the tail of the list such that
tail's next will point to the newly added node. Then, make this new node as the new
tail of the list.

Page 5
C.B. PATEL COMPUTER COLLEGE Data Structure

Consider the above list; node 4 represents the tail of the original list. Let node New
is the new node which needs to be added at the end of the list. Make 4's next to point
to New. Make New as the new tail of the list.

Search an element in a singly linked list

In this program, we need to search a node in the given singly linked list.

To solve this problem, we will traverse through the list using a node current. Current
points to head and start comparing searched node data with current node data. If they
are equal, set the flag to true and print the message along with the position of the
searched node.

For e.g., In the above list, a search node says 4 which can be found at the position 4.

Delete a node from the beginning of the singly linked list

In this program, we will create a singly linked list and delete a node from the
beginning of the list. To accomplish this task, we need to make the head pointer
pointing to the immediate next of the initial node which will now become the new
head node of the list.

Page 6
C.B. PATEL COMPUTER COLLEGE Data Structure

Consider the above example; Node was the head of the list. Make head to point to
next node in the list. Now, node 1 will become the new head of the list. Thus, deleting
the Node.

Delete a node from the middle of the singly linked list

In this program, we will create a singly linked list and delete a node from the middle
of the list. To accomplish this task, we will calculate the size of the list and then
divide it by 2 to get the mid-point of the list. Node temp will point to head node. We
will iterate through the list till midpoint is reached. Now, the temp will point to
middle node and node current will point to node previous to temp. We delete the
middle node such that current's next node will point to temp's next node.

Page 7
C.B. PATEL COMPUTER COLLEGE Data Structure

Consider the above example, mid-point of the above list is 2. Iterate temp from head
to mid-point. Now, temp is pointing to the mid node which needs to be deleted. In
this case, Node is the middle node which needs to be deleted. The node can be
deleted by making node 2's next (current) to point to node 3 (temp's next node). Set
temp to null.

DELETE A NODE FROM THE END OF THE SINGLY LINKED LIST

In this program, we will create a singly linked list and delete a node from the end of
the list. To accomplish this task, we first find out the second last node of the list.
Then, make second last node as the new tail of the list. Then, delete the last node of
the list.

Page 8
C.B. PATEL COMPUTER COLLEGE Data Structure

In the above example, Node was the tail of the list. Traverse through the list to find
out the second last node which in this case is node 4. Make node 4 as the tail of the
list. Node 4's next will point to null.

/*

* Java Program to Implement Singly Linked List

*/

import java.util.Scanner;

/* Class Node */

class Node

protected int data;

protected Node link;

Page 9
C.B. PATEL COMPUTER COLLEGE Data Structure

/* Constructor */

public Node()

link = null;

data = 0;

/* Constructor */

public Node(int d,Node n)

data = d;

link = n;

/* Function to set link to next Node */

public void setLink(Node n)

link = n;

/* Function to set data to current Node */

public void setData(int d)

Page 10
C.B. PATEL COMPUTER COLLEGE Data Structure

data = d;

/* Function to get link to next node */

public Node getLink()

return link;

/* Function to get data from current Node */

public int getData()

return data;

/* Class linkedList */

class linkedList

protected Node start;

protected Node end ;

public int size ;

Page 11
C.B. PATEL COMPUTER COLLEGE Data Structure

/* Constructor */

public linkedList()

start = null;

end = null;

size = 0;

/* Function to check if list is empty */

public boolean isEmpty()

return start == null;

/* Function to get size of list */

public int getSize()

return size;

/* Function to insert an element at begining */

public void insertAtStart(int val)

Node nptr = new Node(val, null);

Page 12
C.B. PATEL COMPUTER COLLEGE Data Structure

size++ ;

if(start == null)

start = nptr;

end = start;

else

nptr.setLink(start);

start = nptr;

/* Function to insert an element at end */

public void insertAtEnd(int val)

Node nptr = new Node(val,null);

size++ ;

if(start == null)

start = nptr;

end = start;

Page 13
C.B. PATEL COMPUTER COLLEGE Data Structure

else

end.setLink(nptr);

end = nptr;

/* Function to insert an element at position */

public void insertAtPos(int val , int pos)

Node nptr = new Node(val, null);

Node ptr = start;

pos = pos - 1 ;

for (int i = 1; i < size; i++)

if (i == pos)

Node tmp = ptr.getLink() ;

ptr.setLink(nptr);

nptr.setLink(tmp);

break;

Page 14
C.B. PATEL COMPUTER COLLEGE Data Structure

ptr = ptr.getLink();

size++ ;

/* Function to delete an element at position */

public void deleteAtPos(int pos)

if (pos == 1)

start = start.getLink();

size--;

return ;

if (pos == size)

Node s = start;

Node t = start;

while (s != end)

t = s;

Page 15
C.B. PATEL COMPUTER COLLEGE Data Structure

s = s.getLink();

end = t;

end.setLink(null);

size --;

return;

Node ptr = start;

pos = pos - 1 ;

for (int i = 1; i < size - 1; i++)

if (i == pos)

Node tmp = ptr.getLink();

tmp = tmp.getLink();

ptr.setLink(tmp);

break;

ptr = ptr.getLink();

size-- ;

Page 16
C.B. PATEL COMPUTER COLLEGE Data Structure

/* Function to display elements */

public void display()

System.out.print("\nSingly Linked List = ");

if (size == 0)

System.out.print("empty\n");

return;

if (start.getLink() == null)

System.out.println(start.getData() );

return;

Node ptr = start;

System.out.print(start.getData()+ "->");

ptr = start.getLink();

while (ptr.getLink() != null)

System.out.print(ptr.getData()+ "->");

Page 17
C.B. PATEL COMPUTER COLLEGE Data Structure

ptr = ptr.getLink();

System.out.print(ptr.getData()+ "\n");

/* Class SinglyLinkedList */

public class SinglyLinkedList

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

/* Creating object of class linkedList */

linkedList list = new linkedList();

System.out.println("Singly Linked List Test\n");

char ch;

/* Perform list operations */

do

System.out.println("\nSingly Linked List Operations\n");

System.out.println("1. Insert at begining");

Page 18
C.B. PATEL COMPUTER COLLEGE Data Structure

System.out.println("2. Insert at end");

System.out.println("3. Insert at position");

System.out.println("4. Delete at position");

System.out.println("5. Check empty");

System.out.println("6. Display");

int choice = scan.nextInt();

switch (choice)

case 1 :

System.out.println("Enter integer element to insert");

list.insertAtStart( scan.nextInt() );

break;

case 2 :

System.out.println("Enter integer element to insert");

list.insertAtEnd( scan.nextInt() );

break;

case 3 :

System.out.println("Enter integer element to insert");

int num = scan.nextInt() ;

System.out.println("Enter position");

int pos = scan.nextInt() ;

Page 19
C.B. PATEL COMPUTER COLLEGE Data Structure

if (pos <= 1 || pos > list.getSize() )

System.out.println("Invalid position\n");

else

list.insertAtPos(num, pos);

break;

case 4 :

System.out.println("Enter position");

int p = scan.nextInt() ;

if (p < 1 || p > list.getSize() )

System.out.println("Invalid position\n");

else

list.deleteAtPos(p);

break;

case 5 :

System.out.println("Empty status = "+ list.isEmpty());

break;

case 6 :

System.out.println("Size = "+ list.getSize() +" \n");

break;

default :

System.out.println("Wrong Entry \n ");

Page 20
C.B. PATEL COMPUTER COLLEGE Data Structure

break;

/* Display List */

list.display();

System.out.println("\nDo you want to continue (Type y or n) \n");

ch = scan.next().charAt(0);

} while (ch == 'Y'|| ch == 'y');

Circular Linked List:

The circular linked list is a kind of linked list. First thing first, the node is an element
of the list, and it has two parts that are, data and next. Data represents the data stored
in the node and next is the pointer that will point to next node. Head will point to the
first element of the list, and tail will point to the last element in the list. In the simple
linked list, all the nodes will point to their next element and tail will point to null.

The circular linked list is the collection of nodes in which tail node also point back
to head node. The diagram shown below depicts a circular linked list. Node A
represents head and node D represents tail. So, in this list, A is pointing to B, B is
pointing to C and C is pointing to D but what makes it circular is that node D is
pointing back to node A.

Page 21
C.B. PATEL COMPUTER COLLEGE Data Structure

Insert a new node at the beginning of the Circular Linked List

In this program, we will create a circular linked list and insert every new node at the
beginning of the list. If the list is empty, then head and tail will point to the newly
added node. If the list is not empty, then we will store the data of the head into a
temporary node temp and make new node as the head. This new head will point to
the temporary node. In simple words, the newly added node will be the first
node(head) and previous head(temp) will become the second node of the list.

After inserting new node to the beginning of the list.

Page 22
C.B. PATEL COMPUTER COLLEGE Data Structure

New represents the newly added node. Earlier A was the head of the list. When new
is added to the beginning of the list, new will become the new head, and it will point
to the previous head, i.e., A.

Insert a new node at the end of the Circular Linked List

In this program, we will create a circular linked list and insert every new node at the
end of the list. If the list is empty, then head and tail will point to the newly added
node. If the list is not empty, the newly added node will become the new tail of the
list. The previous tail will point to new node as its next node. Since it is a circular
linked list; the new tail will point to head. In other words, the new node will become
last node (tail) of the list, and the previous tail will be the second last node.

Page 23
C.B. PATEL COMPUTER COLLEGE Data Structure

After inserting new node to the end of the list

New represents the newly added node. D is the previous tail. When new is added to
the end of the list, it will become new tail and D will point to new.

Insert a new node at the end of the Circular Linked List

In this program, we will create a circular linked list and insert every new node at the
end of the list. If the list is empty, then head and tail will point to the newly added
node. If the list is not empty, the newly added node will become the new tail of the
list. The previous tail will point to new node as its next node. Since it is a circular
linked list; the new tail will point to head. In other words, the new node will become
last node (tail) of the list, and the previous tail will be the second last node.

Page 24
C.B. PATEL COMPUTER COLLEGE Data Structure

After inserting new node to the end of the list

New represents the newly added node. D is the previous tail. When new is added to
the end of the list, it will become new tail and D will point to new.

Search an element in a Circular Linked List

In this program, we create a circular linked list and search a node in the list.

1. 9->5->2->7->3

Consider, above example. Suppose we need to search for node 5. To solve this
problem, we will iterate through the list and compare each node with 5. If match is

Page 25
C.B. PATEL COMPUTER COLLEGE Data Structure

found, we will set the flag to true and prints out the position of the node 5. In this
example, node 5 is present at the position 2.

Delete a node from the beginning of the Circular Linked List

In this program, we will create a circular linked list and delete a node from the
beginning of the list. If the list is empty, print the message "List is empty". If the list
is not empty, we will make the head to point to next node in the list, i.e., we will
delete the first node.

Circular linked list after deleting node from beginning.

Page 26
C.B. PATEL COMPUTER COLLEGE Data Structure

Here, A represents the head of the list. We need to delete a node from the beginning
of the list. So, we will remove A such that B will become new head and tail will
point to the new head.

Delete a node from the end of the Circular Linked List

In this program, we will create a circular linked list and delete a node from the end
of the list. If the list is empty, it will display the message "List is empty". If the list
is not empty, we will loop through the list till second last node is reached. We will
make second last node as the new tail, and this new tail will point to head and delete
the previous tail.

Circular linked list after deleting node from end

Page 27
C.B. PATEL COMPUTER COLLEGE Data Structure

Here, in the above list, D is the last node which needs to be deleted. We will iterate
through the list till C. Make C as new tail and C will point back to head A.

Delete a node from the middle of the Circular Linked List

In this program, we will create a circular linked list and delete a node from the middle
of the list. If the list is empty, display the message "List is empty". If the list is not
empty, we will calculate the size of the list and then divide it by 2 to get the mid-
point of the list. We maintain two pointers temp and current. Current will point to
the previous node of temp. We will iterate through the list until mid-point is reached
then the current will point to the middle node. We delete middle node such that
current's next will be temp's next node.

Identity Matrix

Page 28
C.B. PATEL COMPUTER COLLEGE Data Structure

Circular linked list after deleting node from middle of the list

Consider the above list. Size of the list is 4. Mid-point of the node is 2. To remove
C from the list, we will iterate through the list till mid-point. Now current will point
to B and temp will point to C. C will be removed when B will point to D.

Page 29
C.B. PATEL COMPUTER COLLEGE Data Structure

/*

* Java Program to Implement Circular Singly Linked List

*/

import java.util.Scanner;

/* Class Node */

class Node

protected int data;

protected Node link;

/* Constructor */

public Node()

link = null;

data = 0;

/* Constructor */

public Node(int d,Node n)

data = d;

Page 30
C.B. PATEL COMPUTER COLLEGE Data Structure

link = n;

/* Function to set link to next Node */

public void setLink(Node n)

link = n;

/* Function to set data to current Node */

public void setData(int d)

data = d;

/* Function to get link to next node */

public Node getLink()

return link;

/* Function to get data from current Node */

public int getData()

return data;

Page 31
C.B. PATEL COMPUTER COLLEGE Data Structure

/* Class linkedList */

class linkedList

protected Node start;

protected Node end ;

public int size ;

/* Constructor */

public linkedList()

start = null;

end = null;

size = 0;

/* Function to check if list is empty */

public boolean isEmpty()

return start == null;

Page 32
C.B. PATEL COMPUTER COLLEGE Data Structure

/* Function to get size of list */

public int getSize()

return size;

/* Function to insert an element at begining */

public void insertAtStart(int val)

Node nptr = new Node(val, null);

size++ ;

if(start == null)

start = nptr;

end = start;

else

nptr.setLink(start);

start = nptr;

end.setLink(start);

Page 33
C.B. PATEL COMPUTER COLLEGE Data Structure

/* Function to insert an element at end */

public void insertAtEnd(int val)

Node nptr = new Node(val,null);

size++ ;

if(start == null)

start = nptr;

end = start;

else

end.setLink(nptr);

end = nptr;

nptr.setLink(start);

/* Function to insert an element at position */

public void insertAtPos(int val , int pos)

Page 34
C.B. PATEL COMPUTER COLLEGE Data Structure

Node nptr = new Node(val, null);

Node ptr = start;

pos = pos - 1 ;

for (int i = 1; i < size; i++)

if (i == pos)

Node tmp = ptr.getLink() ;

ptr.setLink(nptr);

nptr.setLink(tmp);

break;

ptr = ptr.getLink();

size++ ;

/* Function to delete an element at position */

public void deleteAtPos(int pos)

if(pos == 1)

Page 35
C.B. PATEL COMPUTER COLLEGE Data Structure

start = start.getLink();

size--;

end.setLink(start);

return ;

if(pos == size)

Node s = start;

Node t = start;

while (s != end)

t = s;

s = s.getLink();

size --;

end = t;

end.setLink(start);

return;

Page 36
C.B. PATEL COMPUTER COLLEGE Data Structure

Node ptr = start;

pos = pos - 1 ;

for (int i = 1; i < size - 1; i++)

if (i == pos)

Node tmp = ptr.getLink();

tmp = tmp.getLink();

ptr.setLink(tmp);

break;

ptr = ptr.getLink();

size-- ;

/* Function to display elements */

public void display()

System.out.print("\nCircular Singly Linked List = ");

if (size == 0)

Page 37
C.B. PATEL COMPUTER COLLEGE Data Structure

System.out.print("empty\n");

return;

//System.out.println(start.getData() );

if (start.getLink() == null || start.getLink() == start)

System.out.println(start.getData() );

return;

Node ptr = start;

System.out.print(start.getData()+ "->");

ptr = start.getLink();

while (ptr.getLink() != start)

System.out.print(ptr.getData()+ "->");

ptr = ptr.getLink();

System.out.print(ptr.getData()+ "\n");

Page 38
C.B. PATEL COMPUTER COLLEGE Data Structure

/* Class CircularSinglyLinkedList */

public class CircularSinglyLinkedList

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

/* Creating object of class linkedList */

linkedList list = new linkedList();

System.out.println("Singly Linked List Test\n");

char ch;

/* Perform list operations */

do

System.out.println("\nSingly Linked List Operations\n");

System.out.println("1. Insert at begining");

System.out.println("2. Insert at end");

System.out.println("3. Insert at position");

System.out.println("4. Delete at position");

System.out.println("5. Check empty");

Page 39
C.B. PATEL COMPUTER COLLEGE Data Structure

System.out.println("6. Display");

int choice = scan.nextInt();

switch (choice)

case 1 :

System.out.println("Enter integer element to insert");

list.insertAtStart( scan.nextInt() );

break;

case 2 :

System.out.println("Enter integer element to insert");

list.insertAtEnd( scan.nextInt() );

break;

case 3 :

System.out.println("Enter integer element to insert");

int num = scan.nextInt() ;

System.out.println("Enter position");

int pos = scan.nextInt() ;

if (pos <= 1 || pos > list.getSize() )

System.out.println("Invalid position\n");

else

list.insertAtPos(num, pos);

Page 40
C.B. PATEL COMPUTER COLLEGE Data Structure

break;

case 4 :

System.out.println("Enter position");

int p = scan.nextInt() ;

if (p < 1 || p > list.getSize() )

System.out.println("Invalid position\n");

else

list.deleteAtPos(p);

break;

case 5 :

System.out.println("Empty status = "+ list.isEmpty());

break;

case 6 :

System.out.println("Size = "+ list.getSize() +" \n");

break;

default :

System.out.println("Wrong Entry \n ");

break;

/* Display List */

list.display();

Page 41
C.B. PATEL COMPUTER COLLEGE Data Structure

System.out.println("\nDo you want to continue (Type y or n) \n");

ch = scan.next().charAt(0);

} while (ch == 'Y'|| ch == 'y');

Page 42

You might also like