版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/artisans/article/details/88925568
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = 0;
ListNode* cur = head;
while (cur)
{
ListNode* TMP = cur->next;
cur->next = pre;
pre = cur;
cur = TMP;
}
return pre;
}
};
//递归版本,返回的head为反转后的头结点
ListNode* reverse2(ListNode* cur, ListNode* & head)
{
if (cur == nullptr) return nullptr;
ListNode * l = reverse2(cur->next, head);
if (head == 0) head = l;
if (l)
{
l->next = cur;
cur->next = 0;
}
return cur;
}