时间限制:1秒 空间限制:32768K 热度指数:378019
本题知识点: 链表
题目描述
输入一个链表,反转链表后,输出新链表的表头。
头插法
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *p= NULL;
ListNode *temp= NULL;
while(pHead!=NULL){
temp=pHead->next;
pHead->next=p;
p=pHead;
pHead=temp;
}
return p;
}
};
双指针 (今天面试被问了,竟然忘了自己做过。。。)
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *p1=NULL;
ListNode *p2=NULL;
if(pHead==NULL)return NULL;
while(pHead!=NULL){
p1=pHead;pHead=pHead->next;
p1->next=p2;p2=p1;
}
return p2;
}
};