LeetCode 24. Swap Nodes in Pairs
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode swapPairs(ListNode head) { if(head == null || head.next == null) return head; ListNode p1 = head; ListNode p2 = head.next; ListNode result = p2; ListNode temp = null; while(p1 != null && p2 != null) { p1.next = p2.next; p2.next = p1; if(temp != null) temp.next = p2; temp = p1; if(p1.next != null && p1.next.next !=null) { p1 = p1.next; p2 = p1.next; } else break; } return result; } }
https://discuss.leetcode.com/topic/4351/my-accepted-java-code-used-recursion/5
public class Solution {
public ListNode swapPairs(ListNode head) {
if ((head == null)||(head.next == null))
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}
}