大家好,我是小庄。我今天报名的算法题是——LeetCode206.逆向链表这道题会用“迭代法”和“递归法”来实现。题目二,具体题目二,实现代码一,思路:迭代法;(1)具体代码/***单链表的定义。*functionListNode(val,next){*this.val=(val===undefined?0:val)*this.next=(next===undefined?null:next)*}*//***@param{ListNode}head*@return{ListNode}*//*思路:迭代法;时间复杂度:O(n);空间复杂度:O(1)*/varreverseList=function(head){letpre=null;让cur=头;让下一个=头;while(cur!==null){next=cur.next;当前.next=pre;前=当前;当前=下一个;}返回前;};(2)运行结果2,方法:递归法;(1)具体代码/***单链表的定义。*functionListNode(val,next){*this.val=(val===undefined?0:val)*this.next=(next===undefined?null:next)*}*//***@param{ListNode}head*@return{ListNode}*//*思路:递归实现;时间复杂度:O(n);空间复杂度:O(n);*/varreverseList=function(head){if(he广告===空||head.next===null){returnhead;}让res=reverseList(head.next);head.next.next=头;head.next=null;returnres;};(2)运行结果3.补充部分注:以下是手动构建完整链表,采用迭代的方式实现functionListNode(val){this.val=val;this.next=null;}functioncreateList(n){让head=null;while(n){让tempNode=newListNode(n);tempNode.next=head;头=临时节点;n--;}returnhead;}??lethead=createList(3);console.log(head);//1->2->3functiongetReverseList(head){letpre=null;让cur=头;让下一个=头;while(cur!==null){next=cur.next;当前.next=pre;前=当前;当前=下一个;}returnpre;}letres=getReverseList(head);console.log(res);//3->2->13.讲解视频点击查看B站讲解视频4.补充偏关注公众号:【深漂程序员小庄】:包含丰富的学习资源和面试经验(不限前端,java),还有学习交流群可以加入,还有各大厂大佬加入交流学习,共同进步~加小庄微信,回复【加群】,可以加入互联网技术交流群。本文由mdnice多平台发布
