206. Reverse Linked List
https://leetcode.com/problems/reverse-linked-list/
https://www.geeksforgeeks.org/reverse-a-linked-list/
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
原地反转
考虑3个元素
1->2->3->null
进行反转的时候,一次操作2个元素。
1.先取出2个元素,current=1,next=2(也就是head.next);
2.先缓存next的next(也就是3), next2=3(也就是next.next)
3.next.next=current;
4.current.next=null; 2->1->null
5.下一次操作取出2个元素,current=2,next=3.
6.需要一个while循环,判断next是否为null。重复执行(2,3,5),第4步只需要在while前面做一次就可以了,如果head.next不为空,就设置为空。
public ListNode ReverseList(ListNode head) { ListNode current = head; ListNode next = current?.next; if (next != null) { head.next = null; } while (next != null) { ListNode next2 = next.next; next.next = current; current = next; next = next2; } return current; }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2018-02-22 base64对文件进行加密
2017-02-22 通信协议中的转义字符
2017-02-22 ImageCollection
2017-02-22 SharedImageCollection