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}.
This topic is somewhat similar to the feeling of a comprehensive problem. Examples are given by comparison. It can be seen that the second half of the list is flipped and then merged with the first half.
Algorithmic analysis:
1. First of all, we should decompose the linked list and divide it into two parts.
2. Inverse the second half of the list.
3. Merge two linked lists.
class Solution {
public:
void reoderList(ListNode* head){
if(head == NULL)
return ;
ListNode* p1 = head;
ListNode* p2 = splitList(head);
p2 = reverseList(p2);
mergelist(p1,p2);
}
ListNode* splitList(ListNode* head){
ListNode* slow = new ListNode(0);
slow->next = head;
ListNode* fast = slow;
while(fast->next && fast->next->next){
slow = slow->next;
fast = fast->next->next;
}
if(fast->next){
slow = slow->next;
fast = fast->next;
}
ListNode* tmp = slow->next;
slow->next =NULL;
return tmp;
}
ListNode* reverseList(ListNode* head){
if(head == NULL)
return head;
ListNode* p=head;
p = head->next;
head->next = NULL;
while(p){
ListNode* tmp = p->next;
p->next = head;
head = p;
p = tmp;
}
return head;
}
void mergelist(ListNode* p1,ListNode* p2){
while(p2){
ListNode* tmp = p2;
p2 = p2->next;
p1->next =p2;
tmp->next = p1->next;
p1 = p1->next->next;
}
}
};
Let's look at the binary tree: Sum of Left Leaves
Calculate the sum of all left subtrees.
This is easy to understand and solve recursively:
int sumOfLeftLeaves(ListNode* root){
if(root == NULL) return 0;
if(root->left =NULL && root->left->left =NULL
&& root->left->right == NULL){
return root->val + sumOfLeftLeaves(root->right);
}
return sumOfLeftLeaves(root->left) +
sumOfLeftLeaves(root->right);
}
Well, that's all for today's parsing.