1、题目描述
输入一个链表,反转链表后,输出新链表的表头。
示例1:
输入
{1,2,3}
返回值
{3,2,1}
说明:本题目包含复杂数据结构ListNode
二、解题
/*
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 *prev=nullptr;
ListNode *curr=pHead;
ListNode *nxt=curr->next;
while(curr !=nullptr)
{
nxt=curr->next;
curr->next=prev;
prev=curr;
curr=nxt;
}
//pHead=p;
return prev;
}
};