Reverse Linked List
来源:互联网 发布:浙江师范行知学院宿舍 编辑:程序博客网 时间:2024/05/20 14:24
Easy Reverse Linked ListMy Submissions
37%
Accepted
Reverse a linked list.
Example
For linked list 1->2->3, the reversed linked list is 3->2->1
Challenge Expand
Tags Expand Reverse it in-place and in one-pass
SOLUTION 1 directly distort the direction of the pointer. BETTER
Oriented the pointer direction to let the current node point to its original previous node. ListNode prev is initialized to Null. At last, we return prev of head is Null.
public class Solution { /** * @param head: The head of linked list. * @return: The new head of reversed linked list. */ public ListNode reverse(ListNode head) { if (head == null || head.next == null) { return head; } ListNode prev = null; while (head != null) { ListNode temp = head.next; head.next = prev; prev = head; head = temp; } return prev; }
SOLUTION 2 Let tail.next to be the new Head.
Add the last to the front.
public class Solution { /** * @param head: The head of linked list. * @return: The new head of reversed linked list. */ public ListNode reverse(ListNode head) { // write your code here if (head == null || head.next == null) { return head; } ListNode tail = head; while (tail.next != null) { ListNode temp = tail.next.next; tail.next.next = head; head = tail.next; tail.next = temp; } return head; }}
0 0
- Single linked list reverse
- reverse a linked list
- Reverse a linked list.
- Reverse a linked list
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Mathematical aspects of finite element I (有限元的数学概念)
- 【编程之美】微软技面心得
- 有序矩阵中查找第k小的元素 Kth smallest element in a row-wise and column-wise sorted 2D array
- [leetcode] Decode Ways
- Remove Duplicates from Sorted List II
- Reverse Linked List
- appcompat_v7 与 actionbarsherlock 冲突解决/移除项目中的appcompat_v7
- python 函数小结
- R apply, lapply, sapply, mapply, tapply functions
- OpenWrt的差异化特性介绍
- Reverse Linked List II
- 接口设备发包
- js表中验证常用正则表达式
- 用Intel HAXM加速Android Emulator