您的位置:首页 > 其它

Leetcode: Reverse Linked List

2015-12-15 11:15 302 查看
Reverse a singly linked list.


Don't forget to consider the case where the linked list is empty

Time: O(2N), Space: O(1)

/**
* 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;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode end = dummy;
while (end.next != null) {
end = end.next;
}
while (dummy.next != end) {
ListNode cur = dummy.next;
ListNode next = cur.next;
cur.next = end.next;
end.next = cur;
dummy.next = next;
}
return dummy.next;
}
}


基本迭代

Time: O(N), Space: O(1)

public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode p1 = head;
ListNode p2 = p1.next;
while(p2 != null){
ListNode tmp = p2.next;
p2.next = p1;
p1 = p2;
p2 = tmp;
}
head.next = null;
return p1;
}
}


基本递归

Time: O(N), Space: O(N)递归栈大小

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
ListNode newHead;

public ListNode reverseList(ListNode head) {
reverse(head);
return newHead;
}

private ListNode reverse(ListNode n){
if( n == null || n.next == null){
newHead = n;
} else {
ListNode prev = reverse(n.next);
prev.next = n;
}
return n;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: