面试题16:反转链表
//题目描述
//
//输入一个链表,反转链表后,输出链表的所有元素。
#include<windows.h>
#include<stack>
#include<iostream>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
// 0ms
//class Solution {
//public:
// ListNode* ReverseList(ListNode* pHead) {
// stack<int>stk=stack<int>();
// ListNode* p=pHead;
// while(p!=NULL){
// stk.push(p->val);
// p=p->next;
// }
// p=pHead;
// while(!stk.empty()){
// p->val=stk.top();
// stk.pop();
// p=p->next;
// }
// return pHead;
// }
//};
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL||pHead->next==NULL)return pHead;
ListNode* p=NULL;
ListNode* q=pHead;
ListNode* r=q->next;
while(r!=NULL)
{
q->next=p;
p=q;
q=r;
r=r->next;
}
q->next=p;
return q;
}
};
int main(){
ListNode* pHead=&ListNode(1);
ListNode*p=pHead;
p->next=&ListNode(2);
p=p->next;
p->next=&ListNode(3);
p=p->next;
p->next=&ListNode(4);
p=p->next;
p->next=&ListNode(5);
p=p->next;
Solution test=Solution();
pHead=test.ReverseList(pHead);
while(pHead!=NULL){
cout<<pHead->val<<" ";
pHead=pHead->next;
}
system("pause");
return 1;
}