Description
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution
mind that the head could be 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 == NULL) return head;
ListNode* cur_head = NULL;
ListNode* cur = head;
ListNode* cur_next = cur->next;
while(cur != NULL)
{
cur_next = cur->next;
cur->next = cur_head;
cur_head = cur;
cur = cur_next;
}
return cur_head;
}
};
结果:
Runtime: faster than 100.00% of C++ online submissions
Memory Usage: less than 54.57% of C++ online submissions
20190331
tbc