Lecture No.03 - LinkList
Lecture No.03 - LinkList
Algorithms
Mr. Tahir Iqbal
[email protected]
A B C
Head
data pointer
Tahir Iqbal, Department of Computer Sciences, BULC
Lists – Another perspective
A list is a linear collection of varying length of
homogeneous components.
list
10 13 5 2
Node *p;
p = new Node;
p - > data = 10;
p - > next = NULL;
p 10
int *p;
p = NULL;
q = new Node; q 6
q - > data = 6;
q - > next = NULL;
p - > next = q; p 10 6
q
Tahir Iqbal, Department of Computer Sciences, BULC
Accessing List Data
Node 1 Node 2
p 10 6
Expression Value
p Pointer to first node (head)
p - > data 10
p - > next Pointer to next node
p - > next - > data 6
p - > next - > next NULL pointer
head lastNodePtr
head 1
ptr
lastNodePtr
Tahir Iqbal, Department of Computer Sciences, BULC
Adding more nodes
for (int i = 2; i < = n; i ++ ) {
ptr = new Node; //create new node
ptr - > data = i;
ptr - > next = NULL;
lastNodePtr - > next = ptr; // order is
lastNodePtr = ptr; // important
}
head 1 2
ptr
lastNodePtr
Tahir Iqbal, Department of Computer Sciences, BULC
Initially
head 1 2
ptr
lastNodePtr
head 1 2
lastNodePtr
ptr 3
lastNodePtr
head 1 2
lastNodePtr
ptr 3
lastNodePtr
head 1 2
lastNodePtr
ptr 3
lastNodePtr
head 1 2
lastNodePtr
ptr 3
head 1 2 3
ptr
lastNodePtr
prevNode currNode
6 ?
ptr
Determine where you want to insert a node. Suppose we
want to insert in ascending order.
Create a new node:
Node *ptr;
ptr = new Node;
ptr - > data = 6;
Tahir Iqbal, Department of Computer Sciences, BULC
Node *ptr, *currNode, *prevNode ;
prevNode = head;
ptr = new Node;
ptr->data = 6;
ptr->next = NULL;
currNode = head->next;
while (currNode->data < ptr->data)
{
prevNode = currNode;
currNode = currNode->next;
}
Note:
when this loop terminates prevNode and currNode are at a
place where insertion will take place. Only the “LINKS” or
pointers of the list need
Tahir Iqbal,to be adjusted
Department in case
of Computer Sciences, BULC of insert.
List after node insert
Now The new link has been added in the linked list
head 2 5 8
6
prevNode ptr
currNode
prevNode delNode
Step 1: Use a pointer that traverse through the list and finds the
previous node of the desired node to be deleted.
head 2 5 8
prevNode
Tahir Iqbal, Department ofdelNode
Computer Sciences, BULC
Finishing the deletion
Step 2: Remove the pointer from the deleted link.
head 2 5 8
prevNodePtr delNode
delete delNode;
Tahir Iqbal, Department of Computer Sciences, BULC
List Operations - Summarized