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.
public class Solution { public ListNode swapPairs(ListNode head) { // Start typing your Java solution below // DO NOT write main() function ListNode offer = new ListNode(0); offer.next = head; ListNode current = offer; ListNode n1 = null; ListNode n2 = null; while(current.next!=null&¤t.next.next!=null){ n1 = current.next; n2 = n1.next; ListNode temp = n2.next; current.next = n2; n1.next = temp; n2.next = n1; current = n1; } return offer.next; } }
public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if( k == 1 || head == null ||head.next == null) return head; ListNode prev = new ListNode(0); prev.next = head; head = prev; ListNode current = prev.next; while(current !=null){ int count = k; while(count>1&& current!= null){ current = current.next; count--; }//check k is valid or not if(current !=null){ current = prev.next; count = k; while(count>1){ ListNode temp = current.next; current.next = temp.next; temp.next = prev.next; prev.next = temp; count--; } prev = current; current = prev.next;//link prev to current } } return head.next; } }
public
ListNode swapPairs(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if(head==null||head.next==null){
return
head;
}
ListNode headnext =head.next;
ListNode headnextnext=headnext.next;
head.next = swapPairs(headnextnext);
headnext.next=head;
return
headnext;
}