JS链表遍历及逆置
interface ILinkedNode {
value: number;
next: LinkedNode | null;
}
class LinkedNode {
value: number;
next: ILinkedNode | null;
constructor(value: number) {
this.value = value;
this.next = null;
}
}
const n1 = new LinkedNode(1);
const n2 = new LinkedNode(2);
const n3 = new LinkedNode(3);
const n4 = new LinkedNode(4);
const n5 = new LinkedNode(5);
const n6 = new LinkedNode(6);
const n7 = new LinkedNode(7);
const n8 = new LinkedNode(8);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
n6.next = n7;
n7.next = n8;
function bianNode(root: ILinkedNode | null) {
if (!root) {
return;
}
console.log(root.value);
bianNode(root.next);
}
function reverseLink(root: ILinkedNode): ILinkedNode {
if (root.next!.next == null) {
root.next!.next = root;
return root.next!;
}
else {
const result = reverseLink(root.next!);
root.next!.next = root;
root.next = null;
return result;
}
}
console.log(reverseLink(n1));