题目描述:
输入一个链表,反转链表后,输出新链表的表头。
解题思路:
递归:
class Solution {
public:
ListNode* ReverseList(ListNode* pHead)
{
//当前结点为空或者是最后一个结点
if(NULL == pHead || NULL == pHead->next)
return pHead;
//先反转后面的链表,走到链表的末端结点
ListNode* p = ReverseList(pHead->next);
//再将当前节点设置为后面节点的后续节点
pHead->next->next = pHead;
pHead->next = NULL;
return p;
}
};
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead)
{
if(NULL == pHead)
return NULL;
ListNode* p = NULL;
ListNode* pNext = NULL;
while(pHead)
{
pNext = pHead->next;
pHead->next = p;
p = pHead;
pHead = pNext;
}
return p;
}
};