写法一:非递归实现。
/**
* 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 * t = head;
head = head->next;
t->next = NULL;
ListNode* tNext = t;
while(head != NULL)
{
t = head;
head = head->next;
t->next = tNext;
tNext = t;
}
return t;
}
};
写法2:递归实现。
/**
* 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* pNewHead = head;
while(pNewHead->next!=NULL)
pNewHead = pNewHead->next;
reverse(head);
return pNewHead;
}
ListNode* reverse(ListNode* head)
{
if(head->next == NULL)
return head;
else
{
ListNode* tail = reverse(head->next);
tail->next = head;
tail = tail->next;
tail->next = NULL;
return tail;
}
}
};
本文详细介绍了链表反转算法的两种实现方式:递归和非递归。通过具体代码实例,深入解析了每种方法的原理、步骤及应用场景,旨在为读者提供全面的理解和实践指导。

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



