π One-stop destination for all your technical interview Preparation π
You are given the head of a singly linked-list. The list can be represented as:
L0 β L1 β β¦ β Ln - 1 β Ln
Reorder the list to be on the following form:
L0 β Ln β L1 β Ln - 1 β L2 β Ln - 2 β β¦
You may not modify the values in the listβs nodes. Only nodes themselves may be changed.
nxt
is the next node of the currNodecurrent node's next
to the top of the stack
.next of the stack's top
to nxt
.curr
to nxt
.last node's next
to NULL
.class Solution {
public:
void reorderList(ListNode* head)
{
int listLen = 0;
stack<ListNode*> stk;
// Count the length & push node in stack.
ListNode* p = head;
while (p) {
listLen++;
stk.push(p);
p = p->next;
}
// Reorder the list.
ListNode* curr = head;
listLen /= 2;
while (listLen--) {
ListNode* stkTop = stk.top();
stk.pop();
ListNode* nxt = curr->next;
curr->next = stkTop;
stkTop->next = nxt;
curr = nxt;
}
// Set last node to NULL
curr->next = nullptr;
}
};
class Solution {
public:
void reorderList(ListNode* head)
{
deque<ListNode*> dq;
ListNode *prev = head, *curr = head->next;
while (curr) {
dq.push_back(curr);
prev->next = nullptr;
prev = curr;
curr = curr->next;
}
curr = head;
while (!dq.empty()) {
curr->next = dq.back();
dq.pop_back();
curr = curr->next;
if (!dq.empty()) {
curr->next = dq.front();
dq.pop_front();
curr = curr->next;
}
}
}
};