题目描述
输入一个链表,反转链表后,输出新链表的表头。
时间限制:1秒 空间限制:32768K 热度指数:383485
本题知识点: 链表
思路
头插法
/*
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* cur) {
if(!cur)
return cur;
ListNode* last=NULL; //上一个,初始值为空
ListNode* temp; //中间变量,p为当前变量
while(cur)
{//调换,先保存当前的变量,再取得下一个变量,然后当前变量指向上一个变量
//更新上一个和当前变量的值
temp=cur;
cur=cur->next;
temp->next=last;
last=temp;
}
return last;
}
};