博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
86. Partition List
阅读量:4692 次
发布时间:2019-06-09

本文共 1379 字,大约阅读时间需要 4 分钟。

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.

 

使用两个链表newHead1, newHead2,遍历原链表,如果结点值小于x,则挂在newHead1上,如果大于等于x,则挂在newHead2上,最后把newHead2挂在newHead1上。

 

1 /** 2  * Definition for singly-linked list. 3  * struct ListNode { 4  *     int val; 5  *     ListNode *next; 6  *     ListNode(int x) : val(x), next(NULL) {} 7  * }; 8  */ 9 class Solution {10 public:11     ListNode* partition(ListNode* head, int x) {12         ListNode* newHead1 = new ListNode(0);13         ListNode* newHead2 = new ListNode(0);14         15         ListNode* pNode1 = newHead1;16         ListNode* pNode2 = newHead2;17         18         ListNode* pNode = head;19         20         while(pNode){21             if(pNode->val < x){22                 pNode1->next = pNode;23                 pNode1 = pNode1->next;24             }else{25                 pNode2->next = pNode;26                 pNode2 = pNode2->next;27             }28             pNode = pNode->next;29         }30         31         pNode2->next = NULL;32         pNode1->next = newHead2->next;33         34         return newHead1->next;35     }36 };

 

转载于:https://www.cnblogs.com/sankexin/p/5874911.html

你可能感兴趣的文章
深度剖析Javascript执行环境、作用域链
查看>>
FHS目录标准配置
查看>>
java-xml解析
查看>>
com技术学习
查看>>
JY游戏之手游《打卡乐猫》
查看>>
HDU-4630 No Pain No Game 树状数组+离线操作
查看>>
面向对象与软件工程—团队作业1
查看>>
常用数组排序方法
查看>>
webstorm 卡死解决方法
查看>>
python基础04 运算
查看>>
面向对象设计模式之五种创建型模式
查看>>
Codeforces GYM 100923G 详解
查看>>
分析Sqlserver与access数据库sql语法的10大差异
查看>>
Java关键字:static
查看>>
单例实现 CGD与条件编译实现单例类
查看>>
关于创建型模式
查看>>
[转]HDFS客户端的权限错误:Permission denied
查看>>
19) Java并发
查看>>
HTTPS的工作原理
查看>>
Java内存和垃圾回收
查看>>