您的位置:首页 > 其它

LeetCode Reverse Linked List

2015-08-22 04:15 411 查看
原题链接在这里:https://leetcode.com/problems/reverse-linked-list/

Iteration 方法:

生成tail = head, cur = tail, while loop 的条件是tail.next != null. 最后返回cur 就好。

Time O(n), Space O(1).

AC Java:

/**
* 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 || head.next == null){
return head;
}
ListNode tail = head;
ListNode cur = head;
ListNode pre;
ListNode temp;
while(tail.next != null){
pre = cur;
cur = tail.next;
temp = cur.next;
cur.next = pre;
tail.next = temp;
}
return cur;
}
}


Recursion 方法:

reverseList(head.next)返回的是从head.next开始的reverse list,把head加在他的尾部即可。

他的尾部恰巧是之前的head.next, 这里用nxt表示。

Recursion 终止条件是head.next == null, 而不是head == null, head==null只是一种corner case而已。

此种方法Time Complexity: O(n), 先下去再回来一共走两遍. Space O(n), 迭代用了stack一共O(n)大小。n 是原来list的长度。

AC Java:

/**
* 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) {
//Method: Recursion
if(head == null || head.next == null){
return head;
}

ListNode nxt = head.next;
ListNode newHead = reverseList(nxt);

nxt.next = head;
head.next = null;
return newHead;
}
}


跟上Reverse Nodes in k-Group.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: