Data Structures and Algorithms Linked List
Data Structures and Algorithms Linked List
Linked List
Lecture 3
1
◼ Arrange dynamically allocated structures
into a new structure called a linked list
◼ Think of a set of children’s pop beads
◼ Connecting beads to make a chain
◼ You can move things around and re-connect
the chain
◼ We use pointers to create the same effect
2
◼ A sequence of nodes linked by pointers:
e
head First Last NULL
next cursor
4
◼ Each of the pointers p, q can point to a
struct of type node:
◼ e.word (string)
◼ e.count (int)
◼ next (pointer to next node)
Struct of type node
word count next
6
p hat 2 ?
q top 3 ?
7
Suppose the address in q is stored in next field of node
pointed to by p and NULL is stored in the last next field:
p hat 2 next
q top 3 NULL
8
◼ Insertion at head of list
◼ Inserting a node after a given node
◼ Insert at end of list
◼ Delete a head node
◼ Delete a non-head node
9
First Last
hat 2 top 3
head
3 2 elType el;
New el.word = “if”;
el.count = 4;
if 4 p = new node;
p-> e = el;
1 p->next = head;
p head = p;
10
cursor
head
if 4 hat 2 top 3
3 2
el.word = “the”;
el.count = 5;
p = new node; p the 5
p-> e = el; New
p-> next = cursor-> next; 1
cursor->next = p;
11
cursor
Last
hat 2 top 3
3
New
p = new node;
2
if 4 p->e = el;
p->next = NULL;
1 cursor->next = p;
p
12
1 cursor
head
2
cursor = head;
head = head->next;
delete cursor;
13
cursor cursor
prev q
Successor
1
hat the top
3
2 Pre:
cursor points to node
prev points to
node *q;
q = cursor;
predecessor node
cursor = cursor->next;
prev->next = cursor;
delete q;
14
http://www.cosc.canterbury.ac.nz/people/
mukundan/dsal/LinkListAppl.html
15
The Circular List:
head tail
cursor
back next
cursor
18