原题链接: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)