剑指offer面试题16 反转链表
来源:互联网 发布:如何在淘宝卖高仿鞋 编辑:程序博客网 时间:2024/06/05 04:14
解题思路:
1.非递归:设置两个指针,一个指针p指向当前节点,一个指针after指向当前节点的下一个节点,从头结点开始遍历链表,交换指针的位置,在交换之前,需要保存下一次after节点的位置,因此需要一个临时变量来存储。最后将原来头部的指针的next设为null。
2.递归:递归的终止条件是当到达原来元链表的尾部时,返回尾指针,也就是新链表的头结点,将head的后一个指针的next域置为head,实现反转操作,并将head的next域置为null。
/** *反转链表 */public class Solution {public ListNode ReverseList(ListNode head) {if(head == null) {return null;}ListNode p = head;ListNode after = head.next;if (after == null) {//证明此时单链表中只有一个节点return head;} else {while (after != null) {//保存after的后一个节点ListNode temp = after.next;//进行指针的交换after.next = p;//p后移,after后移p = after;after = temp;}//最后将尾部的next指针设为nullhead.next = null;return p;} }//递归地实现反转链表public ListNode ReverseList_recursive(ListNode head) {if (head == null || head.next == null) {return head;}ListNode newHead = ReverseList_recursive(head.next);head.next.next = head;head.next = null;return newHead;}}
阅读全文
0 0
- 《剑指Offer》面试题:反转链表
- [剑指offer][面试题16]反转链表
- 【剑指offer】面试题16:反转链表
- 剑指offer 面试题16 反转链表
- 剑指Offer面试题16 反转链表
- 《剑指Offer》面试题16:反转链表
- 《剑指Offer》学习笔记--面试题16:反转链表
- 剑指offer 面试题16—反转链表
- 【剑指Offer学习】【面试题16 :反转链表】
- 剑指offer面试题16-反转链表
- 剑指offer面试题16之反转链表
- 剑指offer:面试题16 反转链表
- 剑指offer-面试题16:反转链表
- 剑指offer之面试题16:反转链表
- 剑指Offer----面试题16:反转链表
- 剑指offer面试题16:反转链表
- 剑指offer--面试题16: 反转链表
- 剑指offer——面试题16:反转链表
- sublime text3 快捷键
- 单元测试 在导入注解@test是报mistch 错误,无法导入原因
- Robotframework(1):配置基础环境
- 读取JPG文件作为caffe网络结构的输入
- 【Mybatis从0到1-014】查询缓存
- 剑指offer面试题16 反转链表
- Linux虚拟内存空间分布
- python --------------网络(socket)编程
- 学奥数对数学究竟有没有帮助?浅谈本人亲身经验
- 8.22 问题 B: 海岛争霸
- Android Input System分析(四)--应用层
- 引用jar包导出excel(数据透视)
- Tensorflow API: Neural network
- idea调试SpringMvc, 出现:java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderL