小视频代码,反转链表的实现思路分析
小视频代码,反转链表的实现思路分析
//思路一: //使用指针 public ListNode ReverseList(ListNode head) { if(head==null || head.next==null){ return head; } ListNode pre=null; ListNode cur=head; while(cur!=null){ ListNode next = cur.next; cur.next = pre; pre=cur; cur=next; } return pre; }
//思路二: //使用递归 public ListNode ReverseList(ListNode head) { if(head==null || head.next==null){ return head; } //tail 是 head.next 链表反转后的最后一个结点 ListNode tail = head.next; //反转 head.next 链表 ListNode next = ReverseList(head.next); head.next = null; //注意:十分重要:head.next 链表反转后,未反转的只有 head 一个结点 tail.next = head; return next; }
以上就是小视频代码,反转链表的实现思路分析, 更多内容欢迎关注之后的文章
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步