【Leetcode】Partition List

46 篇文章 0 订阅
16 篇文章 0 订阅

【题目】

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.


【分析】

其实需要四个指针,初始全部指向root.

思路是用两个链来记录小于x,和大于等于x的数。

small用来记录小链的开头 

large用来记录大链的开头

p1,p2分别用来走大小链,head用来走原始链。

running time O(n)刷一遍链儿

最后把两个链链接,返回small.next;


注意!:到最后的时候要把p2.next清空,= null. 防止有环链形成。!

比如说:1-》5-》2-》6-》1

小链:1-》2-》1

大链:5-》6-》(1)

要把6-》1清空!

注意2:

如果p1,small指向同一个node,那么不管谁控制过这个对象,两个都会有变化。


【代码 】


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode partition(ListNode root, int x) {
        ListNode p1 = new ListNode(0);
		ListNode p2 = new ListNode(0);
		ListNode small = p1;
		ListNode large = p2;
		p1.next = root;
		p2.next = root;
	//	System.out.println("small.next : " + small.next.val);
	//	System.out.println("large.next : " + large.next.val);
		
		while(root!=null){
			if(root.val < x){
				p1.next = root;
				p1 = p1.next;
			}else{
				p2.next = root;
				p2 = p2.next;
			}
			root = root.next;	
		}
		p1.next = large.next;
		p2.next = null;
		return small.next;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值