题目描述
输入一个链表,反转链表后,输出链表的所有元素
思路
比如 1->2->3->4->5 , 5个结点的链表,把2指向1,1指向nullptr,此时需要一个指针指向3,因为2指向了1,链表断开了,需要提前记录3.
code
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
//1.非递归写法,找一个pre,now,next指针
ListNode* ReverseList(ListNode* pHead) {
if(pHead==nullptr)
return nullptr;
ListNode *pNewHead=nullptr;
ListNode *pPre=nullptr;
ListNode *pNow=pHead;
ListNode *pNext=nullptr;
while(pNow!=nullptr){
pNext=pNow->next;
if(pNow->next==nullptr)
pNewHead=pNow;
pNow->next=pPre;
pPre=pNow;
pNow=pNext;
}
return pNewHead;
}
//2.递归写法,一直往后,找到最后一个节点为新的头节点,然后倒着链接。
ListNode* ReverseList(ListNode* pHead) {
if(pHead==nullptr||pHead->next==nullptr)
return pHead;
ListNode *new_head=ReverseList(pHead->next);
pHead->next->next=pHead;
pHead->next=nullptr;
return new_head;
}
};