Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

206. Reverse Linked List

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

1
2
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

1
2
Input: head = [1,2]
Output: [2,1]

Example 3:

1
2
Input: head = []
Output: []

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Non-Recursive
class Solution {
ListNode newHead = null;
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
reverse(head);
return newHead;
}
private ListNode reverse(ListNode head) {
if (head.next == null){
newHead = head;
return newHead;
}

// swap
ListNode temp = reverse(head.next);
temp.next = head;
head.next = null;
return head;
}
}

class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head, prev = null, next = null;
while (cur != null) {
next = cur.next;
cur.next = prev;

// shift to next node
prev = cur;
cur = next;
}
return prev;
}
}

// Recursive
class Solution {
public ListNode reverseList(ListNode head) {
return reverseRec(head, null);
}
private ListNode reverseRec(ListNode head, ListNode newHead) {
if (head == null) return newHead;
ListNode next = head.next;
head.next = newHead;
return reverseRec(next, head);
}
}

Python

反轉串列,把上個,這個,下個順序反轉
遞迴版本就把下個變這個,直到結束
Python語法很方便

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# T:O(n), S:O:(1)
# Definition for singly-linked list.
# class ListNode:
# def init(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev, curr = None, head # end, start
while curr != None:
curr.next, prev, curr = prev, curr, curr.next # reverse curr and prev, curr go next
return prev

# recursive version
class Solution:
def reverseList(self, head):
if head is None or head.next is None:
return head
result = self.reverseList(head.next) # go through
head.next.next,head.next = head,None # reverse
return result

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels