Documente Academic
Documente Profesional
Documente Cultură
START Node
Element
Data Pointer (Link) Null Pointer
Field Field
struct node {
int data;
1 300 5
struct node *link;
};
2 500 0 NULL
struct node my_node;
3
3 100 4
Example:
4 200 1
5 400 2
Conventions of Linked List
There are several conventions for the link to indicate the
end of the list.
1. a null link that points to no node (0 or NULL)
2. a dummy node that contains no item
3. a reference back to the first node, making it a
circular list.
Singly Linked List
10 20 30 40
10
1000 20
2000 30
3000 40
4000 50
START Data Link
PTR = LINK[PTR]
PTR
Search for an Item
Search for an ITEM
Let START be a pointer to a linked list in memory. Write an algorithm
that finds the location LOC of the node where ITEM first appears in
the list, or sets LOC=NULL if search is unsuccessful.
Algorithm
1. set PTR = START
2. repeat step 3 while PTR NULL
3. if ITEM == PTR -> DATA, then
4. set LOC = PTR, and Exit
5. else
6. set PTR = PTR -> LINK
7. set LOC = NULL /*search unsuccessful */
8. Stop
PTR = LINK[PTR]
PTR
Insert an Item
Insertion into a Listed List
Let START be a pointer to a linked list in memory with successive
nodes A and B. Write an algorithm to insert node N between
nodes A and B.
START Node A Node B
Algorithm 1000 2000 3000 4000 5000
1. Set PTR = START
2. Repeat step 3 while PTR NULL
3. If PTR == A, then
4. Set N->LINK = PTR -> LINK (or = B)
5. Set PTR->LINK = N
6. exit START Node A Node B
8. Set PTR=PTR->LINK
9. If PTR == NULL insertion unsuccessful 3500
3 cases: first node, last node, in-between node. (ex: if ITEM = 500? if ITEM = 6000?)
Delete an Item
Deletion from a Linked List
Let START be a pointer to a linked list in memory that contains integer data. Write
an algorithm to delete note which contains ITEM.
Algorithm
1. Set PTR=START and TEMP = START
2. Repeat step 3 while PTR NULL
3. If PTR->DATA == ITEM, then
4. Set TEMP->LINK = PTR -> LINK, exit
5. else
6. TEMP = PTR
7. PTR = PTR -> LINK START Node A Node N Node B
8. Stop
1000 2000 3000 3500 4000 5000
3 cases: first node, last node, in-between node. (ex: if ITEM = 1000? if ITEM = 5000?)
Header Linked Lists
Header linked list is a linked list which always contains a
special node called the Header Node, at the beginning of
the list.
It has two types:
a) Grounded Header List
Last Node Contains the NULL Pointer
b) Circular Header List
Last Node Points Back to the Header Node
Header linked list
13
Grounded Header Link List
A grounded header list is a header list where the last
node contains the null pointer.
The term “grounded” comes from the fact that many
texts use the electrical ground symbol to indicate the
null pointer.
Start
Header Node
BACK Pointer
FORE Pointer
INFO Field
Thank You