ES6版本 链表逆序:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//阅读下面的代码,需要ES6的知识
class Node{//创建节点类
constructor(value){
this.value = value;
this.next = null;
}
setNextNode(node){
this.next = node;
}
getNextNode(){
return this.next;
}
setNodeValue(value){
this.value = value
}
getNodeValue(){
return this.value;
}
}
//创建五个链表节点
const node1 = new Node(1);
const node2 = new Node(2);
const node3 = new Node(3);
const node4 = new Node(4);
const node5 = new Node(5);
//将五个节点连接起来
node1.setNextNode(node2);
node2.setNextNode(node3);
node3.setNextNode(node4);
node4.setNextNode(node5);
//通过递归方式,将链表顺序逆转
function reserveList(root){
//下面的if条件是递归的结束条件
if(root.getNextNode().getNextNode() == null){//判断是否是倒数第二个节点
root.getNextNode().setNextNode(root);//将最后一个节点的next指向倒数第二个节点
return ;
}else{//不是倒数第二个节点
reserveList(root.getNextNode());//继续递归
root.getNextNode().setNextNode(root);//将下一个节点的next指向当前节点
root.setNextNode(null);//将当前节点的next指向null
}
}
//调用逆转链表函数
reserveList(node1);
//通过递归方式,遍历链表函数
function forEachList(node){
if(node == null) return;
console.log(node.getNodeValue());
forEachList(node.getNextNode());
}
//调用遍历链表函数
forEachList(node5);
</script>
</body>
</html>
ES5版本 链表逆序:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//阅读下面的代码,需要ES5的知识
function Node(value){//创建节点类
this.value = value;
this.node = null
}
//创建五个链表节点
var node1 = new Node(1);
var node2 = new Node(2);
var node3 = new Node(3);
var node4 = new Node(4);
var node5 = new Node(5);
//将五个节点连接起来
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
//通过递归方式,将链表顺序逆转
function reserveList(root){
//下面的if条件是递归的结束条件
if(root.next.next == null){//判断是否是倒数第二个节点
root.next.next = root;//将最后一个节点的next指向倒数第二个节点
return ;
}else{//不是倒数第二个节点
reserveList(root.next);//继续递归
root.next.next = root ;//将下一个节点的next指向当前节点
root.next = null;//将当前节点的next指向null
}
}
//调用逆转链表函数
reserveList(node1);
//通过递归方式,遍历链表函数
function forEachList(node){
if(node == null) return;
console.log(node.value);
forEachList(node.next);
}
//调用遍历链表函数
forEachList(node5);
</script>
</body>
</html>