[leetcode] Partition List
来源:互联网 发布:淘宝手机充话费 编辑:程序博客网 时间:2024/05/16 17:10
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
思路:建立两条链,分别将大于x和小于x的结点拼接到两条链后面,然后将两条链连在一起,返回连接在一起之后的头结点
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *partition(ListNode *head, int x) { if(head==NULL) return NULL; if(head->next==NULL) return head; ListNode *start1=NULL,*start2=NULL; ListNode *p1=NULL,*p2=NULL; ListNode *temp=head; while(temp!=NULL){ if(temp->val<x){ if(start1==NULL){ start1=temp; p1=temp; } else{ p1->next=temp; p1=p1->next; } } if(temp->val>=x){ if(start2==NULL){ start2=temp; p2=temp; } else{ p2->next=temp; p2=p2->next; } } temp=temp->next; } if(start1!=NULL){ if(start2!=NULL) { p1->next=start2; p2->next=NULL; } else p1->next=NULL; return start1; } if(start1==NULL){ p2->next==NULL; return start2; } }};
0 0
- LeetCode: Partition List
- LeetCode Partition List
- LeetCode: Partition List
- [Leetcode] Partition List **
- [Leetcode] Partition List
- [LeetCode] Partition List
- leetcode 81: Partition List
- [Leetcode] Partition List
- leetcode 118: Partition List
- [LeetCode]Partition List
- [leetcode]Partition List
- LeetCode-Partition List
- [leetcode] Partition List
- LeetCode - Partition List
- [LeetCode] Partition List
- LeetCode 86: Partition List
- LeetCode:Partition List
- 【leetcode】Partition List
- 黑马程序员-自己总结的winform常用控件(二)
- 迪杰斯克拉--双权值
- 在virtualBox中安装或者升级ubuntu后屏幕分辩率故障
- 游戏对象 (GameObject)
- UVa 1312 Cricket Field 解题报告(枚举 + 离散化)
- [leetcode] Partition List
- 内存泄漏问题
- plupload上传插件在SpringMVC中的整合(JAVA 版)【一】
- myEclipse2014 连接 sqlServer2012 总结
- gpg-agent详细配置
- poj 1018 Communication System
- ruby中in `split': invalid byte sequence in UTF-8 (ArgumentError)解决方法
- 个性化推荐十大挑战
- 变量将被删除。