We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
限制:
解法一: 双指针。代码如下:
/** * 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); } };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
限制:
解法一:
双指针。代码如下:
解法二:
双指针的递归写法。代码如下:
The text was updated successfully, but these errors were encountered: