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.
一道比较简单的题,其实注意好指针的位置这道题就不难做。因为这道题需要两个两个翻转,为了让翻转之后跟上一组的翻转接上,这里最好使用一个dummy node,一开始初始化dummy.next = head; 用一个p 指向dummy 这样 n = p,next. nn = p.next.next 就是每次需要调换位置的节点。在翻转以后, p . next = nn, 这样能够保证节点不会断掉,然后再让p = p.next.next , 让p指向这一组的第二个元素,从而进入下一组交换。
代码:
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode p = dummy;
while(p.next != null && p.next.next != null){
ListNode n = p.next;
ListNode nn = p.next.next;
n.next = nn.next;
nn.next = n;
p.next = nn;
p = p.next.next;
}
return dummy.next;
}