定义数据结构
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