将链表逆转
//非递归
/**
* 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)
return NULL;
ListNode *p,*q;
p = head->next;
head->next = NULL;
while (p != NULL)
{
q = p->next; //保存p的后续节点
p->next = head;
head = p;
p = q;
}
return head;
}
};
递归版本
// Recursive
ListNode* reverseList(ListNode* head)
{
if(head==NULL||head->next==NULL)
return head; // head->next==NULL is the base case for recursion
ListNode* nex = head->next;
head->next=NULL;
ListNode* newHead = reverseList(nex);
nex->next=head;
return newHead;
}
本文详细介绍了链表逆转算法的两种实现方式:非递归和递归版本。通过实例代码解释了如何在不使用额外空间的情况下实现链表逆转,并对比了递归方法的简洁性与效率。
738

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



