Doubly-Linked List Implementation Issues in C
Doubly-Linked List Implementation Issues in C
Page 1 1
Basic Operations on a Doubly-Linked List
1. Add a node.
2. Delete a node.
3. Search for a node.
4. Traverse (walk) the list. Useful for counting
operations or aggregate operations.
Page 3 3
Adding Nodes to an Empty Doubly-Linked List
Initial: Code:
pNew = (struct node *) /*create node*/
pNew malloc(sizeof(struct39
dllnode));
pNew -> data = 39;
pNew -> right = pHead;
pHead
pNew -> left = pHead;
pHead = pNew;
pCur
After:
pNew 39
pHead
pCur
Page 4 4
Adding a Node to the Middle of a Doubly-Linked List
Before:
pNew 64
55 124
pCur
After:
pNew 64
55 124
pCur
Page 5 5
Adding a Node to the Middle of a Doubly-Linked List
The Code
Page 6 6
Adding a Node to the End of a Doubly-Linked List
Before:
pNew 84
55 74
pCur
After:
pNew 84
55 74
pCur
Page 7 7
Adding a Node to the end of a Doubly-Linked List
The Code
pNew = (struct node *) malloc(sizeof(struct dllnode));
pNew -> data = 84;
pNew -> left = pCur;
pNew -> right = pCur -> right;
pCur -> right = pNew;
Page 8 8
Inserting a Node Into a Doubly-Linked List
//insert a node into a linked list
struct node *pNew;
pNew = (struct node *) malloc(sizeof(struct node));
pNew -> data = item;
if (pCur == NULL){
//add before first logical node or to an empty list
pNew -> left = pHead;
pNew -> right = pHead;
pHead = pNew;
}
else {
if (pCur -> right == NULL) {
//add at the end
pNew -> left = pCur;
pNew -> right = pCur -> right;
pCur -> right = pNew;
}
else { //add in the middle
pNew -> left = pCur;
pNew -> right = pCur -> right;
pCur -> right -> left = pNew;
pCur -> right = pNew;
}
}
}
Page 9 9
Deleting a Node from a Doubly-Linked List
Before: Code:
pHead = pCur -> right;
pHead
pCur ->right -> left = NULL;
75 124
free(pCur);
pCur
After:
pHead Recycled 124
pCur
Page 11 11
Deleting a Node from a Linked List – General Case
Before:
75 23 46 12477
pCur
After:
23 Recycled 77
75 124
pCur
Page 12 12
Deleting a Node From a Doubly-Linked List
The Code
//delete a node from a linked list
if (pCur -> left == NULL){
//deletion is on the first node of the list
pHead = pCur -> right;
pCur -> right -> left = NULL;
{
else {
//deleting a node other than the first node of the list
pCur -> left -> right = pCur -> right;
pCur -> right -> left = pCur -> left;
}
free(pCur).
Page 13 13
Searching a Doubly-Linked List
• Notice that both the insert and delete operations on a linked list must
search the list for either the proper insertion point or to locate the node
corresponding to the logical data value that is to be deleted.
Page 14 14
Traversing a Doubly-Linked List
• List traversal requires that all of the data in the list be
processed. Thus each node must be visited and the data value
examined.
• Notice that this is identical code to the singly-linked list except
for the name of the pointer link.
Page 15 15