Leetcode Partition List
2015-08-27 18:18
246 查看
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
return
在这里添加一个头结点,因为不能保证第一个元素是小于X的,通过建立一个头结点,其值为x-1,保证把小于x的节点都
往都节点后面连接。在这里用到三个指针,p指向当前小于x的节点,q指向p之后小于x的节点,frontq指向q的前一个节点。
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given
1->4->3->2->5->2and x = 3,
return
1->2->2->4->3->5.
在这里添加一个头结点,因为不能保证第一个元素是小于X的,通过建立一个头结点,其值为x-1,保证把小于x的节点都
往都节点后面连接。在这里用到三个指针,p指向当前小于x的节点,q指向p之后小于x的节点,frontq指向q的前一个节点。
/** * 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 || head->next == NULL) { return head; } ListNode *H, *p; H = new ListNode(x - 1); H->next = head; p = H; ListNode *q = head; ListNode *temp; ListNode *frontq; bool flag = false; while (p&&q) { if (q->val >= x) { break; } p = p->next; q = q->next; } if (q == NULL) { return H->next; } else { frontq = q; q = q->next; } while (q) { flag = false; if (q->val<x) { temp = q; q = q->next; temp->next = p->next; p->next = temp; p = p->next; frontq->next = q; flag = true; } if (q == NULL) { break; } if (flag == false) { q = q->next; frontq = frontq->next; } } return H->next; } };
相关文章推荐
- JTAG Communications model
- Android端实现用户登录
- 利用MongoDb进行分页方案
- 策略模式——对象行为模式
- mysql 权限管理
- iOS Block
- 关于google的历史纪录和书签
- Handler异步处理机制
- 探讨php中error_log函数输出内容的原子性问题
- 华为OJ(四)
- 数据初始化
- 根据指定的commit查找对应的log
- Emacs命令整理
- Android 4.0新增Space及GridLayout初谈
- [LeetCode] Dungeon Game
- ios 摇一摇
- THINKPHP 中密码在编辑中不填写即不修改,ignore和md5冲突的解决办法
- 黑色星期五
- thinkphp模板中判断变量是否为空
- c/c++之调戏QQ,让QQ无法登陆