Skip to content

Instantly share code, notes, and snippets.

@badboy
Created May 7, 2012 20:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badboy/2630183 to your computer and use it in GitHub Desktop.
Save badboy/2630183 to your computer and use it in GitHub Desktop.
Swapping elements in a double-linked list
class List {
int key;
List next, prev;
}
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;
}
}
@AlexeyKondakov
Copy link

What if b.next == a ?

@Amoodaa
Copy link

Amoodaa commented Dec 5, 2018

What if b.next == a ?

doesnt really make since since the params are the definition here
+this article is 7 years old

@nikunj3011
Copy link

thank u very much

@raksheetbhat
Copy link

Was stuck for a while. This solution helped a lot. Thank you!

@Sketch9920
Copy link

Muchisimas gracias, me ayudo mucho

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment