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 =https://www.cnblogs.com/lanshanxiao/p/ value;
this.next = null;
}
setNextNode(node){
this.next = node;
}
getNextNode(){
return this.next;
}
setNodeValue(value){
this.value =https://www.cnblogs.com/lanshanxiao/p/ 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>
鏈表逆序(ES6版)
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 =https://www.cnblogs.com/lanshanxiao/p/ 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>
鏈表逆序(ES5版)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/60313.html
標籤:JavaScript
上一篇:手摸手帶你理解Vue回應式原理
