题目描述
输入一个链表,反转链表后,输出新链表的表头。
思路:
1.利用一个栈,注意反转后的最后一个元素需要把它的next置为空,否则会无限循环
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL || pHead->next == NULL)
return pHead;
stack<ListNode*> note;
while(pHead->next != NULL){
note.push(pHead);
pHead = pHead->next;
}
ListNode* p = pHead;
ListNode* temp = NULL;
while(!note.empty()){
temp = note.top();
note.pop();
p->next = temp;
p = p->next;
}
p->next = NULL;//反转后的最后一个元素需要把它的next置为空,否则会无限循环
return pHead;
}
};
2. 考虑三个指针pPre,pNode,pNext,分别代表链表中当前节点的前节点,当前节点,当前节点的后节点,变换这三个指针并依次移动即可,注意pNode->next指向pPre时,需要提前记录pNext的位置,否则会使链表断开
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL || pHead->next == NULL)
return pHead;
ListNode* pNode = pHead;
ListNode* pPre = NULL;
ListNode* pReverseHead = NULL;
while(pNode != NULL){
ListNode* pNext = pNode->next;
if(pNext == NULL)
pReverseHead = pNode;
pNode->next = pPre;
pPre = pNode;
pNode = pNext;
}
return pReverseHead;
}
};