题目描述
输入一个链表,反转链表后,输出链表的所有元素。
分析:定义三个指针,分别指向当前遍历到的结点,它的前一个节点,它的后一个节点,然后调整指针指向
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pReversedHead = nullptr;
ListNode* pNode = pHead;
ListNode* pPre = nullptr;
ListNode* pNext = nullptr;
while(pNode)
{
pNext = pNode->next; //保存下一个结点,以防节点断裂,无法访问下一个结点
if(pNext == nullptr)
pReversedHead = pNode;
pNode->next = pPre;
pPre = pNode;
pNode = pNext;
}
return pReversedHead;
}
};