ES6版本 鏈表逆序: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <tit ...
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>鏈表逆序(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 = 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版)