Given a list pairwise exchange with adjacent nodes, and return the list to the exchange. You can not just simply change the internal node values, but need to be the actual node exchange.
Example:
Given 1->2->3->4
, you should return 2->1->4->3
.
1 / * 2 * list data structure . 3 * {public class ListNode . 4 * int Val; . 5 * ListNode Next; . 6 * ListNode (int X) {X = Val;} . 7 *} . 8 * /
Non-recursive solution:
1 class Solution { 2 public ListNode swapPairs(ListNode head) { 3 ListNode pre = new ListNode(0); 4 pre.next = head; 5 ListNode temp = pre; 6 while(temp.next != null && temp.next.next != null) { 7 ListNode start = temp.next; 8 ListNode end = temp.next.next; 9 temp.next = end; 10 start.next = end.next; 11 end.next = start; 12 temp = start; 13 } 14 return pre.next; 15 } 16 }
Recursive solution:
1 class Solution { 2 public ListNode swapPairs(ListNode head) { 3 if(head == null || head.next == null){ 4 return head; 5 } 6 ListNode next = head.next; 7 head.next = swapPairs(next.next); 8 next.next = head; 9 return next; 10 } 11 }
Recursive solution understood that: when the list of hypotheses only two elements, swapPairs (next.next) return null, i.e. head.next = null . = head next.next , and finally return to next node, i.e. the exchange is complete.
When a plurality of elements, swapPairs (next.next) Returns the last next node, repeat the process, i.e., the exchange is complete.