首页 > 代码库 > 一刷leetcode——链表

一刷leetcode——链表

206. Reverse Linked List

题意:将链表转置

我的思路:递归实现,1A

我的代码:

技术分享
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode* head) {
        ListNode* ret = head;
        if (head->next) {
            ret = reverse(head->next);
            head->next->next = head;
        } 
        return ret;
    }
    ListNode* reverseList(ListNode* head) {
        if (head == NULL) return head;
        ListNode* ans, *tmp = head;
        ans = reverse(head);
        tmp->next = NULL;
        return ans;
    }
};
View Code

九章最优解:循环实现,被秒成了渣T T

技术分享
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The new head of reversed linked list.
     */
    ListNode *reverse(ListNode *head) {
        ListNode *prev = NULL;
        while (head != NULL) {
            ListNode *temp = head->next;
            head->next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }
};
View Code

 

一刷leetcode——链表