zoukankan      html  css  js  c++  java
  • [LeetCode] 86. Partition List Java

    题目:

    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的点之前,分别需要保持保持两部分中点的相对位置不变。可以分别得到大于等于x的链表和小于x的链表,然后把两个链表组合起来就是需要的结果。

    代码:

    /**
     * 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) {
            
            ListNode list1=new ListNode(0);
            ListNode list2=new ListNode(0);
            ListNode p1=list1;
            ListNode p2=list2;
            
            ListNode start=head;
            while(start!=null){
                int value=start.val;
                if(value<x){
                    p1.next = start;
                    p1=p1.next;
                    // list1.next=null;
                }else{
                    p2.next = start;
                    p2=p2.next;
                }
                start=start.next;
            }
            p2.next=null;
    
            p1.next=list2.next;
            
            return list1.next;
        }
    }
  • 相关阅读:
    用struct定义函数
    三、OCTAVE画图
    二、OCTAVE 移动数据
    SQL复习
    Flink处理迟到的数据
    LeetCode题目学习
    CentOS7安装pycharm
    IntelliJ IDEA 刷题利器 LeetCode 插件
    Redis命令学习
    项目杂记
  • 原文地址:https://www.cnblogs.com/271934Liao/p/8045988.html
Copyright © 2011-2022 走看看