Professional Documents
Culture Documents
Lecture 4
Introduction
Linked Lists are the second most commonly used storage structures after arrays. A versatile mechanism suitable for use in many kinds of general purpose databases. It can also replace an array as the basis for other storage structures such as stacks and queues. Basically a linked list comprises of a set of data items (links) connected together
2
A Todo List
A Linked List
2.2 5.5
7.7
2.7
In brief
A Linked List
A Linked List
The Link
Data
11
12
77AA55
13
A257AA
222777 77AA55
77AA55
NULL
SOFTWARE TECHNOLOGY I (C++/Data Structures)
Back
14
class Link...
class Link double dData; dData;
15
class Link...
class Link double dData;
data values for this object pointer to the next link object in the list
Link *next;
16
17
18
19
20
A257AA
222777
77AA55 77AA55
first
null
23
first
7.7
5.7
2.7
26
7.7
5.7
2.7
27
7.7
5.7
2.7
28
7.7
5.7
2.7
29
Insert a node...
first id1 dd1 next1 In the constructor set first to null; . . . insertFirst (...) { create a new link node set nodes next field to same thing as first set first to pointer the new node }
SOFTWARE TECHNOLOGY I (C++/Data Structures)
30
insertFirst (...) { create a new link node set nodes next field to same thing as first set first to pointer the new node }
SOFTWARE TECHNOLOGY I (C++/Data Structures)
31
insertFirst (...) { create a new link node set nodes next field to same thing as first set first to pointer the new node }
SOFTWARE TECHNOLOGY I (C++/Data Structures)
32
33
34
first
7.7
5.7
2.7
35
first
7.7
5.7
2.7
36
first
7.7
5.7
2.7
37
38
???
39
first
7.7
5.7
2.7
To display the list, you start at first and follow the chain of pointers from link to link. A variable current points to (or technically refers to) each link in turn. It starts off pointing to first, which holds a pointer to the first link.
40
7.7
2.7
current
41
42
45
46
current
current
current
48
???
Link LinkList::find(double data) { Link current = first; // start at first while (current != NULL) { if (current.dData == data) return current; else current = current.next; } return NULL; } If required item is not in the linked list, a null value is returned.
SOFTWARE TECHNOLOGY I (C++/Data Structures)
50
7.7
5.7
2.7
51
7.7
5.7
2.7
52
What will happen if we are deleting the first element in the Linked List
previous first current
7.7
5.7
2.7
55
What will happen if we are deleting the first element in the Linked List
previous first current
7.7
5.7
2.7
57
If we re going to use lists to implement stacks and queues, what else do we need? Stacks are LIFO Queues are FIFO This suggests we should create a list in which we can insert at the front or the end of the list!
58