Reorder List and Sum of Left Leaves
来源:互联网 发布:plc网络传输器弊端 编辑:程序博客网 时间:2024/05/29 18:01
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. 将后半部分链表倒序。
3. 合并两个链表。
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; } }};
再来看看二叉树:Sum of Left Leaves
计算所有左子树之和。
这个很容易理解,进行递归求解:
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);}
好了,今天的解析到此为止了。
0 0
- Reorder List and Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 在阿里云服务器Ubuntu14.04 64位上安装matlab2014a
- CSS外部样式示例
- 0-1背包(空间优化)
- 【java】使用一维数组实现评委打分功能
- 检索(散列)
- Reorder List and Sum of Left Leaves
- Kubernetes使用Harbor仓库
- POJ 1039 Pipe(直线和线段相交判断,求交点)
- Caffe windows踩坑
- react native使用原生模块
- 蓝桥杯 第八届
- ZOJ3768 Continuous Login
- Idea 将新写的项目中的一个java文件搞成jar包方法
- Java遇到Resource leak: 'input' is never closed怎么解决