Professional Documents
Culture Documents
Algorithm
BESE-2A/B
Lecture 04
Aasma Zahid
Linked List Operations
• Insert a node
– At the start of the list
– At the end of the list
• Delete a node
– At the start of the list
– At the end of the list
• Search
– Find the specified item in linked list
9/17/2012 DSA - Fall 2012 - SEECS, NUST 2
Insertion Corner Case
• Empty List
– With head pointer only
• Head = NULL
– With head and tail pointer only
• Head = Tail = NULL
Insert Item at Start
1. Empty node is created – 1. Node item = new
new node Node();
2. Initialize the value to 2. Item.data = data;
user specified value
3. If list is empty 3. If (head == NULL)
1. Set next pointer to null 1. Item.next = NULL;
2. Set head to new node 2. Head = item;
4. If list is not empty 4. Else
1. Set the next pointer to 1. Item.next = head;
the head
2. Head = item;
2. Set head to new node
Insert Item at Start
• When list is empty
Insert Item at Start
• When list is not empty
Insert item at end
1. Empty node is created 1. Node item = new Node();
2. Initialize the value to 2. Item.data = data;
user specified value
3. When list is not empty 3. If( head == NULL)
1. Set next pointer of new 1. Item.next = NULL;
node to NULL
2. Tail.next = item;
2. Set the next pointer of
last node to the new
node
4. When list is empty 4. Else
1. Set the next pointer of 1. Item.next = NULL;
new node to NULL 2. Head = Tail = item;
2. Set head to new node
Insert Item at End
• When list
is not empty
Delete Item from Start
1. Set tempPtr to head 1. tempPtr = head
2. Set head to next of 2. Head = head->next
itself / tempPtr
3. Delete tempPtr 3. Delete tempPtr
Delete Item from Start
Delete Item from end
1. Find the node just 1. tempPtr->next = tail;
before the start by
traversing the list
2. Delete the last node 2. Delete tail
3. Set tail to current node 3. Tail = node
4. Set next of current 4. tempPtr->next = NULL
node to null
Delete Item from end
Delete Item from end
Deletion Corner Cases
• Empty List
– Prompt user