題目描述
輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
完整代碼
藉助棧來實現
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
//藉助棧實現鏈表的反轉
stack<int> num;
ListNode* p;
p=pHead;
while(p){
num.push(p->val);
p=p->next;
}
p=pHead;
while(p){
p->val=num.top();
num.pop();
p=p->next;
}
return pHead;
}
};
直接反轉指針
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
//原來p->next,指向next,現在讓其指向pre
ListNode* p,*pre,*nextt;
pre=NULL;
p=pHead;
while(p){
nextt=p->next;
p->next=pre;//反轉指針
pre=p;
p=nextt;
}
return pre;
}
};