206. Reverse Linked List

题目:

Reverse a singly linked list.

链接: http://leetcode.com/problems/reverse-linked-list/

2/25/2017, Java

之前的错误:看起来第一遍没有任何问题,但是1->2居然是time limit exceeded。为什么呢?原因是缺了第9行,没有把最后开始的第一个元素的next设为null。这样的话最后两个元素是一个圈。

 1 public class Solution {
 2     public ListNode reverseList(ListNode head) {
 3         if (head == null) return head;
 4         ListNode cur = new ListNode(0);
 5         ListNode next = new ListNode(0);
 6         ListNode prev = new ListNode(0);
 7         prev = head;
 8         cur = head.next;
 9         prev.next = null;
10         while (cur != null) {
11             next = cur.next;
12             cur.next = prev;
13             prev = cur;
14             cur = next;
15         }
16         return prev;
17     }
18 }

别人的算法:用了一个dummy node

dummy的用法是dummy.next其实是prev,这样就跟之前对起来了,而且因为dummy一开始是没有加到list当中去的,最开始dummy.next是null。所以可以免去了前例里面的第9行。注意第7行也是可以的,对Java要熟练哦。

 1 public class Solution {
 2     public ListNode reverseList(ListNode head) {
 3         if (head == null || head.next == null) return head;
 4         ListNode dummy = new ListNode(0);
 5 
 6         while (head != null) {
 7             ListNode tmp = head.next;
 8             head.next = dummy.next;
 9             dummy.next = head;
10             head = tmp;
11         }
12         return dummy.next;
13     }
14 }

之前还用了stack的方法,也是time limit exceeded,没有细究,估计原因是把每个list node放入栈内,但是node中next的值并没有更新。所以无论做了什么,也是然并卵。

5/4/2017

microsoft电面准备

recursive做法

 1 public class Solution {
 2     public ListNode reverseList(ListNode head) {
 3         if (head == null || head.next == null) {
 4             return head;
 5         }
 6         ListNode nextNode = head.next;
 7         ListNode newHead = reverseList(nextNode);
 8         nextNode.next = head;
 9         head.next = null;
10         return newHead;
11     }
12 }

以1->2->3为例

到最底层1-> (null<-2<-3)即1-> (3->2->null)

外层null<-1<-2<-3即3->2->1->null

 

posted @ 2017-02-26 06:07  panini  阅读(159)  评论(0编辑  收藏  举报