Reverse Linked List
2016-12-01 22:13
246 查看
Description:
Reverse a singly linked list.问题描述:
反转链表。—-in place操作,不要新开空间给定链表的头结点,得到反转链表的头结点。
解法一(迭代解法–尾插法)
思路:直观感觉是将链表的指向全部反向,但是要先用临时结点存储后一结点信息,以免反向后找不到后一节点,迭代之前初始化prev空结点来作为reverse后链表的头结点。每轮更新prev和head向前移动。
code:
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 prev = null; while (head != null){ //储存后一结点信息 ListNode tmp = head.next; //指针反向 head.next = prev; //更新prev和head,均向前移动 prev = head; head = tmp; } return prev; } }
解法二(递归解法)
思路:
假设链表有N个结点,先递归颠倒最后N-1个结点,然后小心地将原链表中的首结点插入到结果链表的末端利用递归遍历到链表的尾部
code:
/** * 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) return null; if(head.next == null) return head; ListNode second = head.next; ListNode rest = reverseList(second); second.next =head; head.next = null; return rest; } }
彩蛋:
这个问题在《算法》一书上有深刻阐述(P103—Q1.3.30)相关文章推荐
- LeetCode: Reverse Linked List II
- Reverse Second Half of a Linked List
- LeetCode-206. Reverse Linked List
- 链表---Reverse Linked List
- 206. Reverse Linked List
- leetCode(11):Reverse linked list II
- C实现 LeetCode->Reverse Linked List II (双指针大法)(单链表反转)
- LeetCode | Reverse Linked List II(翻转链表2)
- LeetCode Reverse Linked List II
- 【LeetCode 206: Reverse Linked List】
- 206. Reverse Linked List
- leetcode206~Reverse Linked List
- LeetCode92——Reverse Linked List II
- LeetCode题解——Reverse Linked List
- Reverse Linked List
- LC 206 Reverse a singly linked list.
- Reverse Linked List II
- LeetCode 206. Reverse Linked List
- LeetCode Reverse Linked List I, II详解
- lc面试准备:Reverse Linked List II