翻转链表 剑指 Offer II 024. 反转链表
一、思路1
初始化:pre = head , now = head ,post = head->next
翻转过程:1.now = post , post = post-next,
2. now->next = pre;
3. pre = now
4. 翻转一次完成,直到post指向null 结束
二、代码
if(head==nullptr||head->next==nullptr) return head;
ListNode* now = head , *pre = head ;
ListNode *post = head;
post = post->next;
while(post!=nullptr){
now = post;
post = post->next;
now->next = pre;
if(pre==head)
pre->next = nullptr;
pre = now;
}
return now;
}
三、思路二 栈
1.链表入栈
2.创建新的链表,出栈时加入新链表
ListNode* reverseList(ListNode* head) {
stack<ListNode*> st;
ListNode* p = head;
while(p!=nullptr){
st.push(p);//入栈
p = p->next;
}
ListNode* newhead =new ListNode(0);
p = newhead;
while(st.size()!=0){
ListNode* q = st.top();
st.pop();
q->next = nullptr;//剪短链表
p->next = q;
p = p->next;
}
p->next = nullptr;
return newhead->next;
}