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.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
Seen this question in a real interview before?  YesNo
Difficulty:Medium
Total Accepted:137.2K
Total Submissions:393.7K
Contributor:LeetCode
Subscribe to see which companies asked this question.

Related Topics 
Linked ListTwo Pointers
Java	





1
/**
2
 * Definition for singly-linked list.
3
 * public class ListNode {
4
 *     int val;
5
 *     ListNode next;
6
 *     ListNode(int x) { val = x; }
7
 * }
8
 */
9
class Solution {
10
    public ListNode partition(ListNode head, int x) {
11
        if(head ==null){
12
            return null;
13
        }
14
       ListNode largeHeadNode = null;
15
        ListNode largeTailNode = null;
16
        ListNode lessHeadNode = null;
17
        ListNode lessTailNode  = null;
18
        ListNode temp = head;
19
        while(temp!=null){
20
            if(temp.val >=x ){
21
                if(largeTailNode ==null){
22
                    largeHeadNode = temp;
23
                    largeTailNode = temp;
24
                }else{
25
                    largeTailNode.next = temp;
26
                    largeTailNode  = temp;
27
                }
28
            }else{
29
                if(lessTailNode == null){
30
                    lessTailNode = temp;
31
                    lessHeadNode = temp;
32
                }else{
33
                    lessTailNode.next = temp;
34
                    lessTailNode = temp;
35
                }
36
            }
37
            temp = temp.next;
38
                 
39
        }
40
        if(largeTailNode !=null){
41
            largeTailNode.next = null;
42
        }
43
        if(lessTailNode !=null){
44
            lessTailNode.next = largeHeadNode;
45
        }
46
        if(lessHeadNode == null){
47
            return largeHeadNode;
48
        }
49
        return lessHeadNode;
50
        
51
       
52
        }
53
        
54
   
55
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值