206. Reverse Linked List | Java最短代码实现

来源:互联网 发布:淘宝企业店铺是真货么 编辑:程序博客网 时间:2024/05/17 08:48
原题链接:206. Reverse Linked List

【思路】

本题考查链表的反转。以 1 -> 2 -> 3 -> 4 -> 5 的反转为例,对代码进行剖析:

1、 null  <-  1    <-   2               3       ->     4     ->   5 

                          head      p、q

 2、null  <-  1    <-   2      <-     3              4     ->   5 

                           head        p              q

 3、null  <-  1    <-   2  <-  3                           4     ->   5 

                                   head                   p、q

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;}

T:O(n) S:O(1)  27 / 27 test cases passed. Runtime: 0 ms  Your runtime beats 38.64% of javasubmissions.

【补充】
递归实现

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;}
T:O(n) S:O(n)
欢迎优化!

1 0