题目要求:反转一个单链表。
迭代方法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL)
return NULL;
ListNode* pre = NULL;
ListNode* cur = head;
while(cur != NULL) {
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
递归方法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next)
return head;
ListNode* tail = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return tail;
}
};