写法一:非递归实现。
/**
* 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;
}
}
};