Last active
March 22, 2016 13:22
-
-
Save eknight7/81deb616a054152f572e to your computer and use it in GitHub Desktop.
Sorted Doubly Linked List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Node { | |
int value; | |
Node *prev; | |
Node *next; | |
}; | |
struct DList { | |
Node *head; | |
}; | |
void insert(DList *list, int value) { | |
Node *n = new Node; | |
n->value = value; | |
// Case 1: list is empty | |
if (!list->head) { | |
n->next = NULL; | |
n->prev = NULL; | |
list->head = n; | |
return; | |
} | |
// Case 2: list is non-empty | |
Node *prev = list->head; | |
// we know list->head != NULL | |
Node *cur = list->head->next; | |
while (cur) { | |
if (cur->value > value) | |
break; | |
prev = cur; | |
cur = cur->next; | |
} | |
if (cur) { | |
// Sub-case 1: insert before head | |
if (cur == list->head) { | |
n->next = list->head; | |
list->head = n; | |
return; | |
} | |
// Sub-case 2: insert after head | |
n->next = cur; | |
n->prev = cur->prev; | |
cur->prev = n; | |
n->prev->next = n; | |
} else { | |
// Case 3: List insertion is at end of list | |
// so cur is empty | |
n->next = NULL; | |
n->prev = prev; | |
prev->next = n; | |
} | |
} | |
void delete(DList *list, int value) { | |
Node *cur = list->head; | |
while (cur) { | |
if (cur->value == value) | |
break; | |
cur = cur->next; | |
} | |
// Case 1: delete head | |
if (cur == list->head) { | |
list->head = cur->next; | |
list->head->prev = NULL; | |
delete cur; | |
return; | |
} | |
// Case 2: delete after head if element exists | |
if (cur) { | |
if (cur->prev) | |
cur->prev->next = cur->next; | |
if (cur->next) | |
cur->next->prev = cur->prev; | |
delete cur; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Special case: Insertion at end of list. This is why we need both
prev
andcur
pointers ininsert
.