Last active
March 26, 2022 16:11
-
-
Save dgodfrey206/7092962a5a0ab6fc5aa9e50c9e90bf7a to your computer and use it in GitHub Desktop.
Delete a linked list between two nodes (singly and doubly)
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
void deleteList(node* cur); | |
// Doubly linked list | |
node* deleteBetween(node* head, node* x, node* y) { | |
if (x->prev) | |
x->prev->next = y->next; | |
else | |
head = y->next; | |
if (y->next) | |
y->next->prev = x->prev; | |
y->next = nullptr; | |
deleteList(x); | |
return head; | |
} | |
void deleteList(node* cur) { | |
while (cur) { | |
node* tmp = cur->next; | |
delete cur; | |
cur = tmp; | |
} | |
} | |
// Singly linked list | |
node* deleteBetween2(node* head, node* x, node* y) { | |
node dummy; dummy.next = head; | |
node* cur = &dummy; | |
while (cur->next != x) cur = cur->next; | |
cur->next = y->next; | |
if (y->next) y->next->prev = x->prev; | |
y->next = nullptr; | |
deleteList(x); | |
return dummy.next; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment