LeetCode-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,
Given1->4->3->2->5->2and x = 3,
return1->2->2->4->3->5.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode partition(ListNode head, int x) {
                if(head==null){
            return null;
        }
        ListNode tempListNode=new ListNode(0);
        ListNode secondeListNode=new ListNode(0);
        ListNode firstListNode=tempListNode;
        ListNode second=secondeListNode;
        while(head!=null){
            if(head.val<x){
                firstListNode.next=head;
                firstListNode=firstListNode.next;
            }else{
                second.next=head;
                second=second.next;
            }
            head=head.next;
        }
        firstListNode.next=secondeListNode.next;
                second.next=null;
        return tempListNode.next;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42146769/article/details/89036480