Skip to content

Instantly share code, notes, and snippets.

@daifu
Created March 16, 2013 00:27
Show Gist options
  • Select an option

  • Save daifu/5174273 to your computer and use it in GitHub Desktop.

Select an option

Save daifu/5174273 to your computer and use it in GitHub Desktop.
Given a linked list, swap every two adjacent nodes and return its head.
/*
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
*/
/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null) return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = head;
ListNode ahead = null;
if(head.next != null) {
ahead = head.next;
} else {
return cur;
}
ListNode prev = dummy;
while(ahead != null) {
prev.next = swap(cur, ahead);
prev = cur;
cur = cur.next;
if(cur != null)
ahead = cur.next;
else
ahead = null;
}
return dummy.next;
}
public ListNode swap(ListNode left, ListNode right) {
left.next = right.next;
right.next = left;
return right;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment