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
相邻节点对换。若不是没看完最后一句,我一定是直接对换val的= =
用递归明显简单很多。三个节点,需要对换的两个节点和下一个需要对换的开头节点。 1,2,3 2->1->swap(3)
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode swapnode=head.next;
ListNode nextswap=swapnode.next;
swapnode.next=head;
head.next=swapPairs(nextswap);
return swapnode;
}
}