√
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
迭代的思路:
ListNode* reverseList(ListNode* head) {
if(!head){
return nullptr;
}
ListNode* first = head;//始终指向原链表的首位元素
ListNode* target = head->next;//始终指向即将要放到当前链表首元素之前的目标元素
while(target != nullptr){
first->next = target->next;
ListNode* temp = target->next;
target->next = head;
head = target;
target = temp;
}
return head;
}
作者:sunshy
链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/die-dai-di-gui-jie-fa-by-sunshy/
递归的方法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head)
{
return nullptr;
}
return reverse(head, head, head->next);
}
ListNode* reverse(ListNode* head , ListNode* first, ListNode* target)
{
if(!target)
{
return head;
}
first->next= target->next;
ListNode* temp = target->next;
target->next= head;
return reverse( target, first, temp);
}
};