function ListNode(val) {
this.val = val;
this.next = null;
this.forEach = function(fun) {
var now = this;
fun(now.val);
// loop version
// while(now.next !== null) {
// fun(now.next.val);
// now = now.next;
// }
// recrsion version
if(now.next !== null) {
now.next.forEach(fun);
}
};
}
const head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
head.forEach(console.log);
var swapPairs = function(head) {
now = head;
while (now.next !== null) {
var temp = now.val;
now.val = now.next.val;
now.next.val = temp;
now = now.next.next;
}
return head;
};
console.log("");
const result = swapPairs(head);
result.forEach(console.log);
這是leetcode的swap pairs,雖然不知道為啥他一直說不能存取now.next,如果有人能試成功可以告訴我
原版並沒有forEach,這是我加的,可以看到它有兩個版本的實作方式
初始化串列之後,先印出整個串列
接著swapPairs head,然後把改完的串列再傳給自己,這樣不太好,不過我是要測試能不能有副作用所以這樣寫,比較好的做法是const head,由於JS的const只保證指標不變,所以對const物件的prop改變是可以的,所以可以做成
const result = swapPairs(head);
result.forEach(console.log);
的樣子
沒有留言:
張貼留言