题目来源:牛客网
编程链接
题目描述:
输入一个链表,反转链表后,输出链表的所有元素。
解析:
反转列表主要考察对列表的熟悉程度,有递归和非递归两种写法;
递归代码:
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr||pHead->next == nullptr) //递归退出条件,就是出现空指针
return pHead;
auto pre = ReverseList(pHead->next); //反转到最后一个
pHead->next->next = pHead; 对于每一个被反转的节点,
pHead->next = nullptr;
return pre;
}
};
循坏代码:
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* ReverseHead = NULL;
ListNode* pNode = pHead;
ListNode* pPre = NULL;
while(pNode!=NULL)
{
ListNode* temp = pNode->next;
if(temp==NULL)
ReverseHead=pNode;
pNode->next = pPre;
pPre = pNode;
pNode = temp;
}
return ReverseHead;
}
};