/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
if(head==NULL || head->next==NULL)
return head;
ListNode* pre=head;
ListNode* now=head->next;
ListNode* newHead=NULL;
while(pre && now)
{
ListNode* temp=now->next;
pre->next=newHead;
now->next=pre;
newHead=now;
if(temp==NULL)
return newHead;
else
{
pre=temp;
now=temp->next;
}
}
pre->next=newHead;
return pre;
}
};Reverse Linked List
最新推荐文章于 2025-12-23 22:37:11 发布
本文提供了一种使用C++实现单链表逆序的方法。通过迭代的方式改变链表节点的指向来完成逆序操作。文章包含完整的代码实现,并详细解释了逆序过程中涉及的关键步骤。
1571

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



