Leetcode206:反转链表
思路:用辅助栈和头节点实现先入后出(反转)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//可以用栈啊
stack<ListNode*>stack;
if(!head)
return head;
while(head){
stack.push(head);
head=head->next;
}
ListNode* dump=new ListNode; //建立头节点
ListNode* temp=dump; //头结点索引~
while(!stack.empty()){
dump->next=stack.top();
stack.pop();
dump=dump->next;
}
dump->next=nullptr; //链表不能有两个方向 所以要早点处理掉方向,不能形成1链表形成交互!
return temp->next;
}
};