LeetCode - 206. Reverse Linked List
2018-10-31 20:29
363 查看
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
反转单链表,看到我好几年前通过的代码居然是用List遍历保存之后再倒序遍历反转,然而还RE了好几次。。。往事突然浮现在脑海,没忍住又重写了一下。
耗时0ms
class Solution { public ListNode reverseList(ListNode head) { ListNode cur = head, prev = null, temp = null; while (cur != null) { temp = cur.next; cur.next = prev; prev = cur; cur = temp; } return prev; } }
以前的代码是这样的(耗时464ms):
public class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; ArrayList<Integer> list = new ArrayList<Integer>(); ListNode p = head; while(p!=null) { list.add(p.val); p = p.next; } ListNode q = head; for(int i=list.size()-1; i>=0; i--) { q.val = list.get(i); q = q.next; } return head; } }
相关文章推荐
- LeetCode 206. Reverse Linked List
- LeetCode-206. Reverse Linked List
- 【Leetcode】92. Reverse Linked List II && 206. Reverse Linked List
- LeetCode 206. Reverse Linked List
- Leetcode——206. Reverse Linked List
- Leetcode-206. Reverse Linked List
- 206. Reverse Linked List leetcode list
- Leetcode 206. Reverse Linked List cpp实现
- 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_Add to List 206. Reverse Linked List
- LeetCode-206. Reverse Linked List
- [LeetCode] 206. Reverse Linked List
- LeetCode-206. Reverse Linked List
- LeetCode-206. Reverse Linked List