剑指Offer 16 反转链表
来源:互联网 发布:tv007网络电视手机版 编辑:程序博客网 时间:2024/05/19 14:19
题目描述
输入一个链表,反转链表后,输出链表的所有元素。
思路
就某一个节点来说,我们要将他的next赋给前面的节点,那么原本后面的节点就不见了;所以我们将其保存起来啦
代码
static public ListNode ReverseList(ListNode head) { ListNode currentnode = head; ListNode prev =null; ListNode result=null; while (currentnode!=null) { ListNode next = currentnode.next; if (next ==null) result = currentnode; currentnode.next=prev; prev=currentnode; currentnode=next; } return result; }
递归版
看题就想到了递归,但是递归写起来好难;
public ListNode ReverseList(ListNode head) { if (head==null||head.next==null) //递归结束的条件 return head; ListNode node = ReverseList(head.next);//遍历到最后一个节点 head.next.next=head; head.next=null; return node; //每次都返回node,只不过最后一次才管用 }}
收获
- 别看起来很简单的样子,我想想就知道该怎么办了,但是代码不会写啊;主要因为就是while循环的条件找错了;
- while条件尽量简单,节点尽可能一般化;
- 递归很帅的感觉,但是很难写;
0 0
- 剑指offer 16- 反转链表
- 16链表的反转|剑指offer
- 剑指Offer 16 反转链表
- 剑指offer-16:反转链表
- 【剑指offer】题16:反转链表
- 剑指offer面试16 反转链表
- 剑指offer 16 反转链表
- 剑指offer:反转链表
- 剑指offer--反转链表
- 剑指offer--反转链表
- 剑指Offer-反转链表
- 《剑指offer》反转链表
- 剑指 offer:反转链表
- 剑指offer-反转链表
- 剑指offer 反转链表
- 剑指offer-反转链表
- 剑指offer:反转链表
- [剑指offer]反转链表
- ibatis resultMap参数填充异常:java.sql.SQLException: Column 'XXX' not found.
- 【onsubmit】Form表单onsubmit事件用法详解
- 通过autossh提供内网服务
- 打印三角形
- Linux数据管理——文件锁定
- 剑指Offer 16 反转链表
- linux基本命令和快捷键
- A
- L1-005. 考试座位号
- MySQL 性能优化 20多条
- jQuery的万能动画函数
- 串口通讯中断
- Linux文件目录简介
- c++中如何让程序等待一段时间