【LeetCode】Reverse Linked List 解题报告

Reverse Linked List

[LeetCode]

https://leetcode.com/problems/reverse-linked-list/

Total Accepted: 105474 Total Submissions: 267077 Difficulty: Easy

Question

Reverse a singly linked list.

Ways

面试问到了这个题!当时我说的是最简单的方法!每次找到末尾元素然后翻转。这个明显效率不高!而且我竟然写不出来这个方法!

这里总结一下经验。把listNode中的next改为null可以,但是想把listnode=null就麻烦了。因为你自己定义的listnode=head的话,listnode=null时head并不是空。这个也是清理对象时的经验,只能把最原始的对象赋值为空,要不然原始对象指针会一直占用这个对象。

LeetCode要求递归和非递归方法。非递归我懂了,但是递归的这个我有点看不懂。。

官方解答:https://leetcode.com/articles/reverse-linked-list/

非递归:

Assume that we have linked list 1 → 2 → 3 → Ø, we would like to change it to Ø ← 1 ← 2 ← 3.

While you are traversing the list, change the current node’s next pointer to point to its previous element. Since a node does not have reference to its previous node, you must store its previous element beforehand. You also need another pointer to store the next node before changing the reference. Do not forget to return the new head reference at the end!

public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    ListNode curr = head;
    while (curr != null) {
        ListNode nextTemp = curr.next;
        curr.next = prev;
        prev = curr;
        curr = nextTemp;
    }
    return prev;
}

递归:

1 → … → nk-1 → nk → nk+1 → … → nm → Ø

Assume from node nk+1 to nm had been reversed and you are at node nk.

n1 → … → nk-1 → nk → nk+1 ← … ← nm

We want nk+1’s next node to point to nk.

So,

nk.next.next = nk;

Be very careful that n1’s next must point to Ø. If you forget about this, your linked list has a cycle in it. This bug could be caught if you test your code with a linked list of size 2.

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return p;
}

Date

2016/5/1 12:50:33

你可能感兴趣的:(LeetCode)