Leetcode 86: Partition List

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.

 

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     public int val;
 5  *     public ListNode next;
 6  *     public ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     // this solution doesn't pass OJ but I think it actually solves the problem.
11     public ListNode PartitionInPlace(ListNode head, int x) {
12         if (head == null) return null;
13         
14         ListNode p1 = head, p2 = head;
15         
16         while (p2 != null)
17         {
18             if (p2.val < x)
19             {
20                 if (p1 != p2)
21                 {
22                     var tmp = p1.val;
23                     p1.val = p2.val;
24                     p2.val = tmp;
25                 }
26                 
27                 p1 = p1.next;
28             }
29             
30             p2 = p2.next;
31         }
32         
33         return head;        
34     }
35     
36     public ListNode Partition(ListNode head, int x) {
37         if (head == null) return null;
38         
39         ListNode p1 = new ListNode(1), p2 = new ListNode(2), cur1 = p1, cur2 = p2, cur = head;
40         
41         while (cur != null)
42         {
43             var tmp = cur.next;
44             cur.next = null;
45             if (cur.val < x)
46             {
47                 cur1.next = cur;
48                 cur1 = cur1.next;
49             }
50             else
51             {
52                 cur2.next = cur;
53                 cur2 = cur2.next;
54             }
55             cur = tmp;
56         }
57         
58         cur1.next = p2.next;
59         return p1.next;        
60     }
61 }

 

转载于:https://www.cnblogs.com/liangmou/p/7825098.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值