Last active
December 26, 2019 08:24
-
-
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.
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
/** | |
* 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
iterative method.