【leetcode】【206】Reverse Linked List
来源:互联网 发布:linux命令cat和grep 编辑:程序博客网 时间:2024/04/27 18:20
一、问题描述
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
二、问题分析
这道题,最先想到的是迭代的方式。而迭代又有两种方式:①保持从头访问过的元素先对位置不变,只改变指针的方向,头结点需要单独处理;②指针方向不变,改变元素的位置,即每访问一个新的元素,就把新元素插到头上;
递归的方法其实是从链表的最后边依次改变指针的方向。
三、Java AC代码
迭代①
public ListNode reverseList(ListNode head) { if (head==null || head.next == null) {return head;} ListNode pre = head; ListNode cur = head.next; pre.next = null; ListNode nxt = null; while(cur!=null){ nxt = cur.next; cur.next = pre; pre = cur; cur = nxt; } return pre; }
迭代②
public ListNode reverseList(ListNode head) { if (head==null || head.next == null) {return head;} ListNode pivot = head; ListNode frontier = null; while(pivot.next!=null){ frontier = pivot.next; pivot.next = frontier.next; frontier.next = head; head = frontier; } return head; }
递归
public ListNode reverseList(ListNode head) { if(head == null ||head.next == null){ return head; } ListNode root = reverseList(head.next); head.next.next = head; head.next = null; return root; }
0 0
- LeetCode 206 - Reverse Linked List
- leetcode 206 Reverse Linked List
- LeetCode 206:Reverse Linked List
- leetcode 206: Reverse Linked List
- Reverse Linked List - LeetCode 206
- LeetCode---(206)Reverse Linked List
- LeetCode 206-Reverse Linked List
- leetcode[206]:Reverse Linked List
- Leetcode[206]-Reverse Linked List
- leetcode-206-Reverse Linked List
- LeetCode 206 Reverse Linked List
- leetcode 206:Reverse Linked List
- leetcode-206 Reverse Linked List
- 206、Reverse Linked List [Leetcode]
- Leetcode #206 Reverse Linked List
- leetcode 206: Reverse Linked List
- [LeetCode 206] Reverse Linked List
- [Leetcode]#206 Reverse Linked List
- more is better(并查集)
- 关于AssetBundle、热更新、BestHttp
- listview android:cacheColorHint,android:listSelector属性作用
- Oracle存在则修改,不存在插入记录
- Pku oj 3617 Best Cow Line(贪心)
- 【leetcode】【206】Reverse Linked List
- 关于maven下载jar包失败的问题的总结和解决
- 泛型数据容器Demo
- CUDA7.5+PCL1.8编译教程
- 对于拷贝构造函数和赋值构造函数的理解
- 掌握Tiles 框架 (一)---Tiles入门和Tiles 框架和体系结构
- 个人分析
- 学校Android客户端共享上网的原理
- python2.7配置matplotlib