[leetcode javascript解題]Swap Nodes in Pairs
阿新 • • 發佈:2019-02-01
leetcode 24題 “ Swap Nodes in Pairs”描述如下:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4
, you should return the list as `2->1->4->3.
這道題乍一看不難好像就是兩兩交換位置,改變兩個list的next的指向,然後再移動head指標到下下個連結串列。最初我也是很快這樣做的。
但結果不對,果然單憑腦袋空間想象就容易漏一些細節。於是認真在紙上畫出來才發現,除了改變head和head.next的next指向外,在本次操作還需要改變上一次迴圈最初head指向的節點的next指標。
用圖形表示就是第一步從1->2->3->4
2->1->3->4
,第二步變成2->1->3<-4
因為實際上迴圈中沒有操作值為1的節點的next指標,它還是指向值為3的節點。顯然結果不對。 所以需要一個額外的指標在每次迴圈結束前也就是head指向head.next前,指向head的原位置。然後在下次迴圈時,就能使上一次的head指向下次的head.next。而第一次進行迴圈時,不存在上一個head,所以需要new一個節點。
結果的話如果連結串列裡的長度小於2,直接返回,如果大於等於2,返回最初的head.next就可以了。原理很簡單。
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
if (!head || !head.next) {
return head;
}
var curr = new ListNode(0),
result = head.next;
while (head && head.next) {
var temp = head.next;
curr.next = temp.next;
temp.next = head;
head.next = curr.next;
curr.next = temp;//改變上一個head的next指向
curr = head;//指向當前head所處節點
head = head.next;
}
return result;
};
感覺自己語言描述的比較亂,程式碼比較清晰吧,畫個圖就可以理解,如果有什麼問題歡迎交流。