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 ?
如果这个链表存在头结点,可以将头结点摘下来,然后从第一结点开始,依次插入到头结点后面,即采用头插法建立单链表的思想,直到最后一个结点为止,这样就实现了链表的逆置。
ListNode* reverseList(ListNode* head) {
ListNode* cur = head->next;
head->next = nullptr;
while (cur != nullptr)
{
ListNode* next = cur->next;
cur->next = head->next;
head->next = cur;
cur = next;
}
return head;
}
然而题目中的链表并没有头结点,所以第一个结点就要考虑特殊处理,思路是相同的
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
while(cur != nullptr)
{
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
递归代码,leetcode题解
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head->next == nullptr)
{
return head;
}
ListNode* last = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return last;
}
};
本文详细解析了链表逆置的两种实现方式:迭代和递归。通过具体代码示例,展示了如何通过调整指针顺序来达到逆置链表的目的。适用于初学者理解和掌握链表逆置的基本原理。
1194

被折叠的 条评论
为什么被折叠?



