Created
May 7, 2012 20:26
-
-
Save badboy/2630183 to your computer and use it in GitHub Desktop.
Swapping elements in a double-linked list
This file contains 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
class List { | |
int key; | |
List next, prev; | |
} |
This file contains 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 swap(List a, List b) { | |
if (a == b) | |
return; | |
if (a.next == b) { // right next to each other | |
a.next = b.next; | |
b.prev = a.prev; | |
if (a.next != null) | |
a.next.prev = a; | |
if (b.prev != null) | |
b.prev.next = b; | |
b.next = a; | |
a.prev = b; | |
} else { | |
List p = b.prev; | |
List n = b.next; | |
b.prev = a.prev; | |
b.next = a.next; | |
a.prev = p; | |
a.next = n; | |
if (b.next != null) | |
b.next.prev = b; | |
if (b.prev != null) | |
b.prev.next = b; | |
if (a.next != null) | |
a.next.prev = a; | |
if (a.prev != null) | |
a.prev.next = a; | |
} | |
} |
What if b.next == a ?
doesnt really make since since the params are the definition here
+this article is 7 years old
thank u very much
Was stuck for a while. This solution helped a lot. Thank you!
Muchisimas gracias, me ayudo mucho
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What if b.next == a ?