Skip to content

Instantly share code, notes, and snippets.

@Cee
Created May 21, 2014 08:46
Show Gist options
  • Save Cee/676e46327423d6859553 to your computer and use it in GitHub Desktop.
Save Cee/676e46327423d6859553 to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode p = head;
ListNode q;
ListNode r;
ListNode ret;
if ((p == null) || (p.next == null)){
return head;
}else{
ret = head.next;
q = head.next.next;
head.next = q;
ret.next = head;
p = head;
q = head.next;
while((q != null) && (q.next != null)){
r = q.next.next;
p.next = q.next;
q.next = r;
p.next.next = q;
p = p.next.next;
q = q.next;
}
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment