You are on page 1of 19

CS250 - Data Structures and

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

• Traverse linked list


– Iterate through each item/node

• 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

• Only one item in list


– Set head and tail to NULL
Traverse List
1. Set tempPtr to head
2. If tempPtr is not NULL
– Print node data value
– Set tempPtr to next of itself
– Go to 2
3. Else
– Exit
Search Item in Linked List
• Scan exiting list to find the specified item

1. Get the value to search


2. Set tempPtr to head
3. Check if tempPtr is NULL
4. No
1. If tempPtr data is same as user’s data
• Exit Loop with Success
2. No
• Set tempPtr to tempPtr next value
• Go to 3
5. Yes
1. Exit Loop
Search Item in Linked List
Homework Assignment
• Middle of linked list
– Insert an item
– Delete an item
Questions?

You might also like