程序员面试金典 2.4 链表分割
2016-02-23 17:31
344 查看
题目
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
我的题解
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {} };*/ class Partition { public: ListNode* partition(ListNode* pHead, int x) { // write code here ListNode* small = NULL; ListNode* big = NULL; ListNode* s_cur = NULL; ListNode* b_cur = NULL; ListNode* cur = pHead; while(cur != NULL) { if((cur->val) < x) { if(small == NULL) { small = cur; s_cur = small; } else { s_cur->next = cur; s_cur = s_cur->next; } } else { if(big == NULL) { big = cur; b_cur = big; } else { b_cur->next = cur; b_cur = b_cur->next; } } cur = cur->next; } if(s_cur == NULL) return big; s_cur->next = big; if(b_cur != NULL) b_cur->next = NULL; return small; } };
相关文章推荐
- [C/C++]反转链表
- 关于指针的一些事情
- 开发人员、程序员与计算机科学家三者之间的区别
- 只有程序员看的懂的面试圣经|如何拿下编程面试
- 下一次技术面试时要问的 3 个重要问题
- 程序员必备,程序员四大忌
- 程序员们,做好你手里的俩份试卷
- 程序员必备的10大健康装备! 我们要工作更要健康!
- C#实现基于链表的内存记事本实例
- C#中struct和class的区别详解
- 一篇关于程序员性格的文章第1/3页
- PHP程序员面试 切忌急功近利(更需要注重以后的发展)
- 8种类型极品程序员,不知你属于哪一种?
- C# Pointer指针应用实例简述
- 程序员编程从初级到中级的10个秘诀
- C++智能指针实例详解
- 做一个优秀程序员应该知道的15件事
- C++指向函数的指针实例解析
- 关于c语言指针的两处小tip分享
- 浅析iterator与指针的区别