LeetCode206. ๅ่ฝฌ้พ่กจ๐๐๐๐๐็ฎๅ
้ฎ้ขๆ่ฟฐ
ๅๆ้พๆฅ๏ผ206. ๅ่ฝฌ้พ่กจ
็ปไฝ ๅ้พ่กจ็ๅคด่็น head ๏ผ่ฏทไฝ ๅ่ฝฌ้พ่กจ๏ผๅนถ่ฟๅๅ่ฝฌๅ็้พ่กจใ
็คบไพ 1๏ผ

่พๅ
ฅ๏ผhead = [1,2,3,4,5]
่พๅบ๏ผ[5,4,3,2,1]
็คบไพ 2๏ผ

่พๅ
ฅ๏ผhead = [1,2]
่พๅบ๏ผ[2,1]
็คบไพ 3๏ผ
่พๅ
ฅ๏ผhead = []
่พๅบ๏ผ[]
ๆ็คบ๏ผ
- ้พ่กจไธญ่็น็ๆฐ็ฎ่ๅดๆฏ
[0, 5000] -5000 <= Node.val <= 5000
ไปฃ็ ๅฎ็ฐ
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
Python
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
newHead = self.reverseList(head.next)
head.next.next = head
head.next = None
return newHead
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next){
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
};
Go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
newHead := reverseList(head.Next)
head.Next.Next = head
head.Next = nil
return newHead
}