DS 7
DS 7
2 4 6 7
head
Node
•Data
•Link (pointer): used to store the address of the next node.
Linked Representation
head
8 BAT 3 CAT 4 FAT 0 0
1
2
3 CAT 4
4 FAT 0
5
6
head 7
8 8 BAT 3
9
Insertion
1
2 Find the address of CAT
3 CAT 6 1) Set the link of BAT to EAT.
3
4 FAT 0 2) Deallocate CAT
5
6 EAT 4
head 7
8 8 BAT 3
8 BAT 6
9
Linked List Creation
struct listNode
{
int data; head
listNode* Link;
};
data link
//in main()
struct listNode *head = new
listNode;
Inserting First Element
while(tempNode)
{
if(tempNode->Link == NULL)
{
tempNode->Link = newlistNode;
return;
}
tempNode = tempNode->Link;
}
}
Adding an Item before another Item?
8 BAT 3 CAT 4
6 FAT 0
a EAT 4
• Typical operations
• Initialize the list
• Destroy the list
• Determine if list empty
• Search list for a given item
• Insert an item
• Delete an item, and so on
Insertion
• Insert a node
– Four cases
• Case 1: Insertion in an empty list
• Case 2: Insertion at the beginning of a nonempty
list
• Case 3: Insertion at the end of a nonempty list
• Case 4: Insertion somewhere in a nonempty list
– Cases 1 and 2 requirement: Change value of
the pointer first
– Cases 3 and 4: After inserting an item, count
incremented by one
Deletion
• Delete a node
• Four cases
– Case 1: The list is empty
– Case 2: The item to be deleted is in the first node of
the list, which would require us to change the value of
the pointer first
– Case 3: The item to be deleted is somewhere in the
list
– Case 4: The item to be deleted is not in the list
Stacks & Queue Revisit
Linked Stack
data link
top Pop
B
Pop
Push D
D
A
E 0
Linked Queue
B C D A E 0
Pop
Pop
Push E
Summary