定義資料結構
interface LinkNode {
val : number;
next : this;
}
class LinkNode implements LinkNode {
constructor(number) {
this.val = number;
}
}
定義資料工廠函式
function createLink() {
let arr = [new LinkNode(1), new LinkNode(2), new LinkNode(3)];
// 使得每一個LinkNode的next連結起來
arr.map((e, index, array) => {
if (index < array.length - 1) {
e.next = array[index + 1];
} else {
e.next = null;
}
// or e.next=(index<array.length-1)?array[index+1]:null);
})
return arr;
}
反轉函式
const reverse_Link = (head : LinkNode) => {
let next = null,
prev = null;
while (head != null) {
next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
結果
let testLink = createLink();
console.log(testLink);
console.log(reverse_Link(testLink[0]));
/*
[ LinkNode { val: 1, next: LinkNode { val: 2, next: [Object] } },
LinkNode { val: 2, next: LinkNode { val: 3, next: null } },
LinkNode { val: 3, next: null } ]
LinkNode { val: 3,
next: LinkNode { val: 2, next: LinkNode { val: 1, next: null } } }
*/
參考資料 https://blog.csdn.net/xyh269/article/details/70238501