Given the head of a singly linked list, reverse the list, and return the reversed list.
Q:单链表反转
Constraints:
- The number of nodes in the list is the range [0, 5000].
- -5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
Example 1:
**Input:** head = [1,2,3,4,5]**Output:** [5,4,3,2,1]
Example 2:
**Input:** head = [1,2]**Output:** [2,1]
Example 3:**Input:** head = []**Output:** []
方法1:循环+头插
/*** 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 == nullptr || head->next == nullptr){return head;}// 使用带额外头结点的新链表ListNode* newHead = new ListNode();ListNode* p = head;ListNode* q = nullptr;while(p != nullptr){// 遍历旧链表,将旧链表的结点一个个以头插的方式加入到新链表中q = p->next;p->next = newHead->next;newHead->next = p;p = q;}p = newHead->next;delete newHead;newHead = nullptr;return p;}};
运行效率评价
Success Details
Runtime: 8 ms, faster than 63.09% of C++ online submissions for Reverse Linked List.
Memory Usage: 8.4 MB, less than 41.66% of C++ online submissions for Reverse Linked List.
方法2:递归法
实现代码:
/*** 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 == nullptr || head->next == nullptr){return head;}ListNode* last = reverseList(head->next);head->next->next = head;head->next = nullptr;return last;}};
代码图解:
运行效率
Success Details
Runtime: 8 ms, faster than 63.09% of C++ online submissions for Reverse Linked List.
Memory Usage: 8.4 MB, less than 20.51% of C++ online submissions for Reverse Linked List.
