Linked List - 1
Linked List - 1
node
A
Head
Conceptual diagram
A
Head
A B C
Head
Head
struct Node
{
int data; // data
Node* link; // pointer to next
};
node
data link
Department of Computer Science
;
Creating single Linked List
We use two important pointers, i.e. head and
tail
head points to first node
tail points to last node.
Demo
25, 50,90,40,55
Department of Computer Science
Operations on single Linked List
1. Create a node
node *temp=new node;
temp->data=value;
temp->link=head;
3. Make headt point to the new node (i.e the node that node points to)
head=temp;
Department of Computer Science 4-29
Inserting a Node at the front
tail 300
3. Make tail point to the new node (i.e the node that node points to)
650
head
500
cur tail
cur=head;
cur 500
Department of Computer Science 4-35
;
Inserting a Node at Specific
for(int i=1;i<pos;i++)
{ tail
pre pre=cur;
cur
} cur=cur->link;
for(int i=1;i<pos;i++)
{ tail
pre=cur;
pre cur
} cur=cur->link;
temp->data=value; tail
pre cur
85 600 65 650
700 50 800 40 NULL
85 600 65 650
700 50 800 40 NULL
tail
head 500
Step -2 head=head->link;
Step -3 delete temp
Department of Computer Science 4-43
;
Deleting a node from end
In the case find a node that comes before the
last node.
This can be achieved by traversing the linked list.
We would make two temporary pointers(previous and
current) and let them move through the whole linked
list.
At the end, the previous node will point to the second
to the last node and the current node will point to the
last node, i.e. node to be deleted.
We would delete current node and make the
previous node as the tail.
cur next
pre