Leetcode Partition List 分割链表
来源:互联网 发布:北京11选5遗漏数据查询 编辑:程序博客网 时间:2024/06/10 04:36
题目:
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
.
分析:
对于值大于等于x的节点,直接插到链表。对于值小于x的节点,需要找到第一个大于等于x的节点,插到它的前面。
Java代码实现:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode partition(ListNode head, int x) { if(head==null || head.next==null) return head; ListNode dummy = new ListNode(0); ListNode node = dummy; node.next = null; while(head!=null) { if(head.val>=x) { while(node.next!=null) { node = node.next; } node.next = new ListNode(head.val); node.next.next = null; } else { while(node.next!=null && node.next.val < x) { node = node.next; } ListNode temp = node.next; node.next = new ListNode(head.val); node.next.next = temp; } node = dummy; head = head.next; } return dummy.next; }}
0 0
- Leetcode Partition List 分割链表
- Partition List 分割链表
- [LeetCode] Partition List 分割单链表
- 86. Partition List&链表分割
- 86. Partition List(分割链表)--M
- LeetCode | Partition List(partition方法处理链表)
- Partition List 链表划分区间@LeetCode
- LeetCode(Partition List) 划分链表
- leetcode Partition List二分链表问题
- LeetCode Partition List(链表分段)
- Leetcode 86. Partition List(链表划分)
- 【LeetCode】Partition List 链表划分
- leetcode:Partition List (链表处理)【面试算法题】
- LeetCode Partition List 按值分段链表 系统分析
- 闲话链表(三) leetcode之Partition List
- LeetCode OJ 之 Partition List (划分链表)
- [LeetCode] Partition List(!!!!巧妙的链表插入)
- [LeetCode-86] Partition List (链表数据分区)
- Maven简介
- linux下jar命令和eclipse两种方式生成wordcount.jar包和hadoop下wordcount实例的运行
- HDU 5115 Dire Wolf
- Python 字符串方法详解
- LeetCode 202 : Happy Number
- Leetcode Partition List 分割链表
- 蓝桥杯--- 历届试题 邮局 (深搜+暴力)(动态待解决)
- Leetcode[3] Longest Substring Without Repeating Characters
- 九度1014排名(结构体)
- 算法设计读书笔记第二章
- hdu 1757 A Simple Math Problem 矩阵快速幂
- Egret Wing实战教程
- 初步使用HTMLParser工具包【部分代码来自网络】
- RMAN duplicate数据库