Skip to content

Instantly share code, notes, and snippets.

@guolinaileen
Last active December 26, 2019 08:24
Show Gist options
  • Save guolinaileen/4653975 to your computer and use it in GitHub Desktop.
Save guolinaileen/4653975 to your computer and use it in GitHub Desktop.
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) {
if(head==null) return null;
if(head.next==null) return head;
ListNode previous=null;
ListNode current=head;
ListNode runner=head.next;
while(runner!=null && runner!=current)
{
current.next=runner.next;
runner.next=current;
if(previous==null)
{
previous=runner;
head=previous;
previous=previous.next;
}else
{
previous.next=runner;
previous=previous.next.next;
}
current=current.next;
if(current==null) break;
runner=runner.next.next.next;
}
return head;
}
}
@guolinaileen
Copy link
Author

iterative method.

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