zoukankan      html  css  js  c++  java
  • 分隔链表

    此博客链接:https://www.cnblogs.com/ping2yingshi/p/14227560.html

    分隔链表

    题目链接:https://leetcode-cn.com/problems/partition-list/

    题目

    给你一个链表和一个特定值 x ,请你对链表进行分隔,使得所有小于 x 的节点都出现在大于或等于 x 的节点之前。

    你应当保留两个分区中每个节点的初始相对位置。

    示例:

    输入:head = 1->4->3->2->5->2, x = 3
    输出:1->2->2->4->3->5

    题解

    找链表中某些数字比某个数子大或者小的问题,可以使用两个链表来解题,第一个链表中存小于给定数的链表中的数,第二个链表中存大于给定数的链表中的数,然后把小链表的尾部指向大链表的头部,最后把大链表的尾部置空。

    代码

    class Solution {
        public ListNode partition(ListNode head, int x) {
             ListNode small=new ListNode(0);
             ListNode smallp=small;
             ListNode lager=new ListNode(0);
             ListNode lagerp=lager;
             while(head!=null)
             {
                 if(head.val<x)
                 {
                     smallp.next=head;
                     smallp=smallp.next;
                 }
                 else
                 {
                     lagerp.next=head;
                     lagerp=lagerp.next;
                 }
                 head=head.next;
             }
             smallp.next=lager.next;
             lagerp.next=null;
             return small.next;
    
        }
    }

    结果

    出来混总是要还的
  • 相关阅读:
    html 简介
    MySQL事务等了解知识
    MySQL—navicat&&练习&&pymysql
    MySQL查询表(一)
    作业
    MySQL约束&&表关系
    mysql数据类型
    初识mysql
    dll 原理解析
    又过了一天
  • 原文地址:https://www.cnblogs.com/ping2yingshi/p/14227560.html
Copyright © 2011-2022 走看看