Q2.4 Partition List
来源:互联网 发布:中铁建沙特知乎 编辑:程序博客网 时间:2024/05/01 19:49
Q:Write code to partiton a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x.
A:双链表,其中一个记录小于x的置的节点,剩下的节点记录在第一个链表下,最后将第一个链表的尾节点指向第二个链表的head
#include <iostream>using namespace std;struct ListNode { int val;ListNode *next; ListNode(int x) : val(x), next(NULL) {} };ListNode *init(int a[], int n) { ListNode *head = NULL; ListNode *p = NULL; for (int i = 0; i < n; i++) { ListNode *cur = new ListNode(a[i]); if (i == 0) { head = cur; p = cur; } p->next = cur; p = cur; } return head;}ListNode *partition(ListNode *head, int x) { ListNode small_dummy(-1); ListNode big_dummy(-1); ListNode *small = &small_dummy; ListNode *big = &big_dummy; for (ListNode *cur = head; cur; cur = cur->next) { if (cur->val < x) { small->next = cur; small = small->next; } else { big->next = cur; big = big->next; } } small->next = big_dummy.next; big->next = NULL; return small_dummy.next;}void printList(ListNode *head) {ListNode *p = head;for( ; p; p = p->next) {cout<<p->val<<" ";}cout<<endl;}int main() {int a[10] = {1,4,3,2,5,2};ListNode *head = init(a, 6);printList(head);head = partition(head, 3);printList(head);return 0;}
0 0
- Q2.4 Partition List
- Q2.4
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- centos添加用户
- 2004
- 当析构函数遇到多线程 ── C++ 中线程安全的对象回调
- 使用 Python 开始游戏开发
- centos nginx设置多站点
- Q2.4 Partition List
- linux下解压命令大全
- poj 3255(次短路)
- 关于JAVA中GUI界面切换的问题
- golang interface赋值
- 排序算法三:插入排序
- Seo总结--不断完善
- 用 Python 做个简单的井字游戏
- DTD和Schema