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?
Companies:
Microsoft, Facebook, Apple, Mathworks, Bloomberg, Adobe, Amazon, Yandex, Goldman Sachs, Google, Baidu, Nvidia, Expedia, Yahoo, Cisco
Related Topics:
Linked List
Similar Questions:
// OJ: https://leetcode.com/problems/reverse-linked-list/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode dummy(0);
while (head) {
ListNode *node = head;
head = head->next;
node->next = dummy.next;
dummy.next = node;
}
return dummy.next;
}
};