Skip to content

[剑指 Offer] 24. 反转链表 #58

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
frdmu opened this issue Jul 31, 2021 · 0 comments
Open

[剑指 Offer] 24. 反转链表 #58

frdmu opened this issue Jul 31, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Jul 31, 2021

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

 

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

限制:

  • 0 <= 节点个数 <= 5000

解法一:
双指针。代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head) return head;

        ListNode *cur = head, *prev = nullptr;
        while (cur) {
            ListNode* tmp = cur->next;
            cur->next = prev;
            prev = cur;
            cur = tmp;
        }   
        return prev;       
    }
};

解法二:
双指针的递归写法。代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* recursive(ListNode* cur, ListNode* prev) {
        if (!cur) return prev;

        ListNode* res = cur->next;
        cur->next = prev;
        prev = cur;
        cur = res; 
        return recursive(cur, prev);    
    }
    ListNode* reverseList(ListNode* head) {
        return recursive(head, nullptr);             
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant