Given a linked list, swap every two adjacent nodes and return its head.
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { /** * @param head a ListNode * @return a ListNode */ public ListNode swapPairs(ListNode head) { // Write your code here if(head == null || head.next == null) return head; ListNode fakehead = new ListNode(0); fakehead.next = head; ListNode prev = fakehead; ListNode curr = head; ListNode next = head.next; while(next != null && next.next != null){ curr.next = next.next; next.next = curr; prev.next = next; curr = curr.next; next = curr.next; prev = prev.next.next; } if(next != null){ curr.next = next.next; next.next = curr; prev.next = next; } return fakehead.next; } }
lintcode-easy-Swap Nodes in Pairs
原文:http://www.cnblogs.com/goblinengineer/p/5249354.html