链表划分
来源:互联网 发布:mt4 一键下单脚本源码 编辑:程序博客网 时间:2024/06/11 06:15
题目描述:给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。你应该保留两部分内链表节点原有的相对顺序。
样例:给定链表 1->4->3->2->5->2->null,并且 x=3,返回 1->2->2->4->3->5->null
思路:分别申请两个指针left和right,小于x的添加到 left中,大于等于x的添加到right中;最后,将 right链接到left的末端即可
代码如下:
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */class Solution {public: /** * @param head: The first node of linked list. * @param x: an integer * @return: a ListNode */ ListNode *partition(ListNode *head, int x) { // write your code here if(head == NULL)return head; ListNode *left = NULL,*right = NULL,*cur = head; ListNode *r=NULL,*l=NULL; while(cur){ if(cur->val <x){ if(left == NULL){ left = cur; l = left; } else{ l->next = cur; l = cur; } } else{ if(right == NULL){ right = cur; r = right; } else{ r->next = cur; r = cur; } } cur = cur->next; } if(r != NULL)r->next = NULL; if(l !=NULL){ l->next = right; return left; } else{ return right; } }};
阅读全文
0 0
- 链表划分
- 链表划分
- 题目:链表划分
- LintCode-链表划分
- 链表划分
- 链表划分
- LintCode:链表划分
- 链表的划分
- 链表:链表划分
- 链表划分
- 链表划分
- Lintcode 链表划分
- 链表划分
- LintCode 链表划分
- 链表划分-LintCode
- 链表划分
- 链表划分
- 链表划分
- hdu5463---King's Game
- redis实战之计数信号量(未完)
- Java中的Lambda表达式
- RAISR(Rapid and Accurate Super Image Resolution)
- 过滤器的原理及配置
- 链表划分
- 算法实现:二进制老鼠测毒
- Android 应用内分屏查看(使用fragment)
- Linux服务(DNS)
- 【SpringCloud】(十四):Feign对Hystrix的支持 fallbackFactory
- window10安装nodejs出现2503,2502错误的解决方法
- 【二分图匹配入门专题1】A
- Mysql联表查询、查询近期某段时间内的数据等
- 设计模式——工厂方法模式