LeetCode 206. Reverse Linked List(翻转链表)
来源:互联网 发布:浅野菌子淘宝 编辑:程序博客网 时间:2024/05/16 04:55
原题网址:https://leetcode.com/problems/reverse-linked-list/
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?
方法一:迭代。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode reverseList(ListNode head) { if (head == null || head.next == null) return head; ListNode current = head.next; ListNode prev = head; prev.next = null; while (current.next != null) { ListNode next = current.next; current.next = prev; prev = current; current = next; } current.next = prev; return current; }}
方法二:递归。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { private ListNode reversed; private void reverse(ListNode prev, ListNode node) { if (node == null) return; reversed = node; ListNode next = node.next; node.next = prev; reverse(node, next); } public ListNode reverseList(ListNode head) { if (head == null || head.next == null) return head; reverse(null, head); return reversed; }}
0 0
- LeetCode 206. Reverse Linked List(翻转链表)
- leetcode 206. Reverse Linked List(翻转链表)
- LeetCode | Reverse Linked List II(翻转链表2)
- LeetCode 92. Reverse Linked List II(翻转链表)
- 206. Reverse Linked List--链表翻转
- LeetCode 92 Reverse Linked List II(翻转链表II)(Linked List)(*)
- Reverse Linked List II 局部翻转链表@LeetCode
- [LeetCode] Reverse Linked List I II - 链表翻转问题
- 【LeetCode】 Reverse Linked List 翻转链表 ( Uber,FB )
- 【LintCode】 Reverse Linked List 翻转链表
- [Java]Reverse Linked List 链表翻转
- Reverse Linked List 翻转链表
- LeetCode_206. Reverse Linked List-翻转链表
- Reverse Linked List 翻转链表
- 35.Reverse Linked List-翻转链表(容易题)
- [LeetCode] 翻转子链表 reverse linked list
- LeetCode.206. Reverse Linked List(反转有序链表)
- Leetcode 92. Reverse Linked List II 翻转链表2 解题报告
- LeetCode LeetCode 205. Isomorphic Strings(同形词)
- Leetcode_347_Top K Frequent Elements
- MAC,IP,路由传输封装过程
- 【BZOJ1854】【codevs3358】游戏,二分图最大匹配
- Linux script and scriptreplay(三)
- LeetCode 206. Reverse Linked List(翻转链表)
- linux core文件
- 数据研发工程师实习面试问题记录一
- mysql 登录、退出
- ASP.NET 状态管理(视图状态 ViewState)
- tda2822功放
- Unity3D入门(rolling ball)——学习笔记
- Spark笔记一之启动、简单RDD、提交、测试
- jQuery的ajax使用场景讨论(c#)