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.
题意 : 交换相邻两个节点
此题不难,但是出错的地方 就在于 不要把引用搞混了,p = q 把q赋给p,此时p也指向同一块内存
如果此时p 对 这块内存的修改,q也能够看见 ,但是如果p = t ,那么等价的就是p现在指向了另一块内存
此时你觉得p的影响会影响到q吗,明显不会,这就是为什么要建立父指针的原因所在!
public class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) return head; ListNode parent = head; ListNode son = head; int count = 0; while (son != null && son.next != null) { ListNode tmp = son.next; son.next = tmp.next; tmp.next = son; if (count == 0) { head = tmp; count = 1; } else { parent.next = tmp; } parent = tmp.next; son = parent.next; } return head; } }