• 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.

    根据x,将小于x的节点放在大于x节点的前面。。

    正常思路就行:新建两个链表,一个存放大于x的,一个存放小于x的。最后连接起来。注意写代码的一些细节。最后节点(大链表的最后一个)的next要设为null

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode partition(ListNode head, int x) {
            if(head==null||head.next==null) return head;
            ListNode small=new ListNode(0);
            ListNode big=new ListNode(0);
            ListNode s=small,b=big;  //用来遍历添加节点
            while(head!=null){
                if(head.val>=x){
                    b.next=head;
                    b=b.next;
                }else{
                    s.next=head;
                    s=s.next;
                }
                head=head.next;
            }
            b.next=null;   //大的最后一个节点的next要设为null,这一步一定不能忘记。不然它还是会指向原来的next。
            s.next=big.next;
            return small.next;
        }
    }
  • 相关阅读:
    Android编译系统
    Android指针管理:RefBase,SP,WP
    Android图片异步加载
    Android动画学习笔记Android Animation
    触发checkbox的click事件时遇到的问题
    C++ Primer笔记
    Android自定义对话框(Dialog)位置,大小
    android startService流程梳理笔记
    自定义SimpleAdapter
    Android Touch事件
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8214236.html
Copyright © 2020-2023  润新知