分隔链表

此博客链接: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;

    }
}

结果

出来混总是要还的
原文地址:https://www.cnblogs.com/ping2yingshi/p/14227560.html