题目描述
输入一个链表,反转链表后,输出新链表的表头。
方法一:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr || pHead->next == nullptr)
return pHead;
ListNode* pReverseHead = nullptr;
ListNode* pNode = pHead;
ListNode* preNode = nullptr;
while(pNode != nullptr)
{
ListNode* pNext = pNode->next;
if(pNext == nullptr)//得到尾节点
pReverseHead = pNode;
pNode->next = preNode;//更新指针域使其反转
preNode = pNode;
pNode = pNext;
}
return pReverseHead;
}
};
方法二:递归,只是输出尾节点为头节点
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr || pHead->next == nullptr)
return pHead;
ListNode* pReverseHead = ReverseList(pHead->next);
pHead->next->next = pHead;
pHead->next = nullptr;
return pReverseHead;
}
};