自己解法
链表问题的关键在于,要理解引用赋值,实际上是指针的赋值,链表是典型的指针组成的数据结构,理解了next是地址指针赋值后,就可以清楚地进行指针交换了。
这个题有个坑的地方在于,第3个节点要直接先取下来,后续循环的时候才好用,还有就是,结尾要赋空指针。
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null) {
return head;
}
ListNode virtualHead = new ListNode(-1);
ListNode temp = virtualHead;
while (head != null && head.next != null) {
ListNode m = head.next.next;
temp.next = head.next;
temp = temp.next;
temp.next = head;
temp = temp.next;
head = m;
}
temp.next = head;
return virtualHead.next;
}
}
官方解法
官方解法也是迭代和递归,这里只贴递归,迭代是用了两个临时节点,进行了交换,类似数的赋值,利用第一个指针的next去维护第3个指针的位置。
递归的思路类似,第一个节点的next指向第3个节点的递归结果,第二个指针的next指向第一个指针,返回第二个指针。
class Solution {
public ListNode swapPairs(ListNode head) {
// If the list has no node or has only one node left.
if ((head == null) || (head.next == null)) {
return head;
}
// Nodes to be swapped
ListNode firstNode = head;
ListNode secondNode = head.next;
// Swapping
firstNode.next = swapPairs(secondNode.next);
secondNode.next = firstNode;
// Now the head is the second node
return secondNode;
}
}