Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes’ values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
解题思路:
(1)将链表结点压入一个栈中;
(2)然后头尾依次次各一个地加入链表
class Solution {
public:
void reorderList(ListNode* head) {
if (head == NULL)
return;
stack<ListNode*> Stack;
ListNode* pNode = head;
while (pNode != NULL)
{
Stack.push(pNode);
pNode = pNode->next;
}
int len = Stack.size();//链表中结点的个数
pNode = head;
ListNode* pNext = NULL;
ListNode* temp = NULL;
len--;
while (len)
{
if (pNode->next != NULL)
pNext = pNode->next;
else
break;
//取栈顶元素加入链表
temp = Stack.top();
Stack.pop();
pNode->next = temp;
len--;
if (len == 0)
{
temp->next = NULL;
return;
}
else
temp->next = pNext;
pNode = pNext;
len--;
}
pNode->next = NULL;
}
};