举个例子:
用例子给出方法的基本思想
1->2->3
放入stack<ListNode*> 为 (为了方便,这里简单的用val去表示)
3(栈顶)
2
1(栈底)
current = head
根据 current->next 取到 2,,用 tmp = 2(这里2 还有后面的next ,即为 3)
head->next = 3
将3 出栈
放入 current后面,变成 1->3,此时 current->next->next 等于 NULL
————————
变成
2(栈顶)
1(栈底)
————————
current->next->next == tmp ,即为 1->3->2
current = tmp ,(current =2)
current == 栈顶元素 2,所以终止 while(条件不符合)
********************************************************************************
偶数个元素
用if(tmphead->next->next == current) break; 跳出while终止
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if(head == NULL) return;
stack<ListNode*> stk;
ListNode* tmphead = head;
ListNode* current;
while(tmphead != NULL){
stk.push(tmphead);
tmphead = tmphead->next;
}
tmphead = head;
// tmphead != stk.top() 用来作为链表元素为 奇数个 终止条件
while((tmphead != NULL)&&(tmphead != stk.top())){
current = tmphead->next;// 2 3
tmphead->next = stk.top();//1->5 2->4
stk.pop();// top is 4 3
if(tmphead->next->next == current) break;//用来作为链表元素为 偶数个 终止条件
tmphead->next->next = current;// 1->5->2
tmphead = current; //tmphead is 2
}
if(tmphead != NULL)
tmphead->next = NULL;
}
};