3/28/2018 Compiled by worku w.
2
A structure with a pointer to itself as a member
Used for linked lists, queues, stacks and trees
struct node
{
int data; data next
node *next;
}; node
node *p , *q ; 3 next next
p data q data
10
p = new node;
q = new node;
p -> data = 3;
q -> data = 10; q
p -> next = q;
p 3
data next data next
q -> next = NULL; 10
q = NULL;
Array-based Implementation
Fixed Size
Items Have A Physical Ordering
Costly Insertions and Deletions
Constant Access Time
Pointer-based Implementation
Able to Grow as Needed
Items have a Logical Ordering
Insertions and Deletions are Simple
Time to Access the Ith Node Depends on I
Flexible space use
Dynamically allocate space for each element as
needed
Include a pointer to the next item
Each node could be a structure
Linked list
Each node of the list contains
the data item
a pointer to the next node
Data Next
How to Represent
End of the List (node whose next is NULL)
Beginning of the List (node pointed to, by Head)
Add first item
Allocate space for node
Set Next to NULL
Set Head to point to new node
Head
5 8
Data Next Data Next
Figure 4-1
(a) A linked list of integers; (b) insertion; (c) deletion
Figure 4-2
A pointer to an integer
Figure 4-3a
(a) Declaring pointer variables; (b) pointing to statically allocated memory; (c)
assigning a value
Figure 4-3b
(d) Allocating memory dynamically; (e) assigning a value; (f) copying a pointer
Figure 4-3c
(g) Allocating memory dynamically and assigning a value; (h) assigning NULL to a
pointer variable; (i) deallocating memory
Figure 4-4
An incorrect pointer to a deallocated node
Figure 4-5a
Programming with pointer variables and dynamically allocated memory
Figure 4-5b
Programming with pointer variables and dynamically allocated memory
Figure 4-5c
Programming with pointer variables and dynamically allocated memory
Figure 4-5d
Programming with pointer variables and dynamically allocated memory
A node in a linked list is usually a struct
struct Node{
int item;
Node *next; Figure 4.6 A node
};
A node is dynamically allocated
Node *p;
p = new Node;
Compiled by worku w.
Figure 4-6
A node
The head pointer points to the first node in a linked list
Figure 4.7 A head pointer to a list
If head is NULL, the linked list is empty
Figure 4.8 A lost cell
Compiled by worku w.
Reference a node member with the -> operator
p->item;
A traverse operation visits each node in the linked
list
A pointer variable cur keeps track of the current node
for (Node *cur = head; cur != NULL;
cur = cur->next)
cout << cur->item << endl;
Compiled by worku w.
Figure 4.9
The effect of the assignment cur = cur->next
Compiled by worku w.