Вы находитесь на странице: 1из 27

Data Structures

Linked List Operations

• Introduction
• Traversing a Linked List
• Searching a Linked List
• Memory Allocation & Garbage Collection
• Overflow and Underflow
• Review Questions
• A linked list (One-way list) is a linear collection of data
elements, called nodes, where the linear order is given by
means of pointers.

• Each node is divided into two parts.

• First part contains the information of the element.

• Second part contains the address of the next node in the list.
Traversing a Linked List
• PTR is a pointer variable which points to the node currently
being processed.
• LINK [PTR] points to the next node to be processed.

 Algorithm (Traversing a linked list)

1. Set PTR = START. [Initialize pointer PTR]

2. Repeat step 3 and 4 while PTR ≠ NULL.
3. Apply PROCESS to INFO[PTR].
4. Set PTR = LINK [PTR]. [PTR points to next node]
[End of Step 2 Loop.]
• Write an algorithm to modify each element of an integer
linked list such that
(a) each element is double of its original value.
(b) each element is sum of its original value and its previous element.

• Write an algorithm to find out the maximum and minimum

data element from an integer linked list.
Searching a Linked List
Searching a Linked List (1)
 List is Unsorted
1. Set PTR = START.
2. Repeat Step 3 While PTR ≠ NULL.
3. If ITEM = INFO [PTR], then:
Set LOC = PTR, and EXIT.
Set PTR = LINK [PTR]. [PTR points to next node]
[End of if Structure.]
[End of step 2 Loop.]
4. Set LOC = NULL. [Search is Unsuccessful.]
5. Exit . [Return LOC and Exit.]
Searching a Linked List (2)
 List is Sorted
1. Set PTR = START.
2. Repeat Step 3 While PTR ≠ NULL.
3. If ITEM > INFO [PTR], then:
PTR = LINK [PTR]. [PTR points to next node]
Else if ITEM = INFO [PTR], then:
Set LOC = PTR, and EXIT. [Search is successful.]
Set LOC = NULL, and EXIT. [ITEM exceeds INFO[PTR]…]
[End of if Structure.]
[End of step 2 Loop.]
4. Return LOC .
5. Exit.
Memory Allocation
• Together with the linked list, a special list is maintained
which consists of unused memory cells.

• This list has its own pointer.

• This list is called List of available space or Free-storage

list or Free pool.
Free Pool
• Linked list with free pool or list of Available space.

2 A 6
3 E 9
AVAIL 4 10 C 7
5 8
6 B 4
7 D 3
8 1
9 F 0

10 5
Garbage Collection
• Garbage collection is a technique of collecting all the
deleted spaces or unused spaces in memory.

• The OS of a computer may periodically collect all the

deleted space onto the free-storage list.

• Garbage collection may take place when there is only

some minimum amount of space or no space is left in free
storage list.

• Garbage collection is invisible to the programmer.

Garbage Collection Process
• Garbage collection takes place in two steps.

1. The computer runs through all lists tagging those cells

which are currently in use.

2. Then computer runs through the memory, collecting all

the untagged spaces onto the free storage list.
Overflow and Underflow
 Overflow: When a new data are to be inserted into a data
structure but there is no available space i.e. the free storage
list is empty.

• Overflow occurs when AVAIL = NULL, and we want insert

an element.

• Overflow can be handled by printing the ‘OVERFLOW’

message and/or by adding space to the underlying data
Overflow and Underflow
 Underflow: When a data item is to be deleted from an
empty data structure.

• Underflow occurs when START = NULL, and we want to

delete an element.

• Underflow can be handled by printing the ‘UNDERFLOW’

1. Nth node from end of a Linked List

Maintain two pointers – reference

pointer and main pointer. Initialize both
reference and main pointers to head.
First, move reference pointer to n nodes
from head. Now move both pointers one
by one until the reference pointer
reaches the end. Now the main pointer
will point to nth node from the end.
Return the main pointer.
Middle Element of a Linked List
• Method 1:
Traverse the whole linked list and count the no. of
nodes. Now traverse the list again till count/2 and
return the node at count/2.

• Method 2:
Traverse linked list using two pointers. Move one
pointer by one and other pointer by two. When the
fast pointer reaches end slow pointer will reach
middle of the linked list.
Ravi Kant Sahu, Asst. Professor @ Lovely
Professional University, Punjab (India)
Number of times a given int occurs in a list

• 1. Initialize count as zero.

• 2. Loop through each element of linked list: a)
If element data is equal to the passed number
then increment the count.
• 3. Return count.

Ravi Kant Sahu, Asst. Professor @ Lovely

Professional University, Punjab (India)
To Check Loop in a Linked List

Approach using Mark Visited Nodes: This solution requires modifications to the basic
linked list data structure.
Have a visited flag with each node. 
Traverse the linked list and keep marking visited nodes. 
If you see a visited node again then there is a loop. This solution works in O(n) but
requires additional information with each node.
A variation of this solution that doesn’t require modification to basic data structure can
be implemented using a hash, just store the addresses of visited nodes in a hash and if
you see an address that already exists in hash then there is a loop
Floyd’s Cycle-Finding Algorithm: This is the fastest method and has been described
Traverse linked list using two pointers. 
Move one pointer(slow_p) by one and another pointer(fast_p) by two. 
If these pointers meet at the same node then there is a loop. If pointers do not meet
then linked list doesn’t have a loop
To find length of loop in a Linked List
• We know that Floyd’s Cycle detection algorithm
 terminates when fast and slow pointers meet at a
common point. We also know that this common point is
one of the loop nodes (2 or 3 or 4 or 5 in the above
diagram). We store the address of this common point in a
pointer variable say ptr. Then we initialize a counter with
1 and start from the common point and keeps on visiting
next node and increasing the counter till we again reach
the common point(ptr). At that point, the value of the
counter will be equal to the length of the loop.
Singly Linked List is Palindrome
• (By reversing the list)
This method takes O(n) time and O(1) extra space.
1) Get the middle of the linked list.
2) Reverse the second half of the linked list.
3) Check if the first half and second half are
4) Construct the original linked list by reversing
the second half again and attaching it back to the
first half.

Remove Duplicates from a Sorted linked List

• Traverse the list from the head (or start) node.

While traversing, compare each node with its
next node. If data of next node is same as
current node then delete the next node.
Before we delete a node, we need to store
next pointer of the node
Remove Duplicates from Unsorted Linked List
• Method 1:-This is the simple way where two loops are used. Outer loop is used to pick the
elements one by one and inner loop compares the picked element with rest of the
• Method2:-
In general, Merge Sort is the best-suited sorting algorithm for sorting linked lists
1) Sort the elements using Merge Sort. We will soon be writing a post about sorting a linked
list. O(nLogn)
2) Remove duplicates in linear time using the 
algorithm for removing duplicates in sorted Linked List. O(n)
Please note that this method doesn’t preserve the original order of elements.
Time Complexity: O(nLogn)
• METHOD 3 (Use Hashing)
We traverse the link list from head to end. For every newly encountered element, we
check whether it is in the hash table: if yes, we remove it; otherwise we put it in the hash

Ravi Kant Sahu, Asst. Professor @ Lovely

Professional University, Punjab (India)
Swap nodes in a Linked List without
swapping data
• This may look a simple problem, but is interesting question as it has
following cases to be handled.
1) x and y may or may not be adjacent.
2) Either x or y may be a head node.
3) Either x or y may be last node.
4) x and/or y may not be present in linked list.
• How to write a clean working code that handles all of the above possibilities.
• We strongly recommend to minimize your browser and try this yourself
• The idea it to first search x and y in given linked list. If any of them is not
present, then return. While searching for x and y, keep track of current and
previous pointers. First change next of previous pointers, then change next
of current pointers. 
Move last element to front of a Linked List
• Write a function that moves the last element to the front in
a given Singly Linked List. For example, if the given Linked
List is 1->2->3->4->5, then the function should change the
list to 5->1->2->3->4.
• Algorithm:
Traverse the list till last node. Use two pointers: one to store
the address of last node and other for address of second last
node. After the end of loop do following operations.
i) Make second last as last (secLast->next = NULL).
ii) Set next of last as head (last->next = *head_ref).
iii) Make last as head ( *head_ref = last)
Reverse a Linked List
• Initialize three pointers prev as NULL, curr as head and next as NULL.
• Iterate trough the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = curr->next// Now change next of current
// This is where actual reversing happens
curr->next = prev
• // Move prev and curr one step forward
prev = curr
curr = next
Delete last occurrence of an item from linked
Loop through the whole list and use a double
pointer to keep track of the node containing
the address of last occurrence node.
Review Questions
• Write an algorithm to find out the maximum and minimum
data element from an integer linked list.

• What is the condition of Overflow and underflow?

• What are the steps followed during garbage collection?