rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

206. 反转链表 #16

Open rocksc30 opened 1 year ago

rocksc30 commented 1 year ago
/**
 * 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 last = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return last;
    }
}
Ni-Guvara commented 1 year ago
/**
 * 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) {
         // 1 -> 2 -> 3 
        if(!head || head->next == nullptr)
            return head;

        ListNode * p = head->next; 
        ListNode * tail = reverseList(head->next);
        head->next = nullptr;
        p -> next = head;
        return tail;
    }
};