206. Reverse Linked List
Total Accepted: 89431
Total Submissions: 232505
Difficulty: Easy
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
iteratively:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (NULL == head || NULL == head->next) return head;
ListNode* p = head;
ListNode* q = head->next;
ListNode* ans = head;
while (NULL != q) {
p = q->next;
q->next = ans;
ans = q;
q = p;
}
head->next = NULL;
return ans;
}
};
recursively:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (NULL == head || NULL == head->next) return head;
ListNode *p = head->next;
ListNode *ans = reverseList(p);
head->next = NULL;
p->next = head;
return ans;
}
};