力扣面试150题--分隔链表

day 39

题目描述

思路

遍历链表,每一个点与值比较,比值小就继续,比值大就放到链表尾部即可

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        if(head==null){
            return null;
        }
        ListNode fakehead=new ListNode();
        fakehead.next=head;
        ListNode z=head;
        while(z.next!=null){
            z=z.next;
        }
        ListNode before=fakehead;
        ListNode y=head;
        ListNode end=z;
        while(y!=end){
            if(y.val>=x){
                z.next=y;
                before.next=y.next;
                y=y.next;
                z=z.next;
                z.next=null;
            }
            else{
                before=before.next;
                y=y.next;
            }
        }
        if(y.val>=x){
                z.next=y;
                before.next=y.next;
                y=y.next;
                z=z.next;
                z.next=null;
            }
        return fakehead.next;
    }
}
相关推荐
电子_咸鱼1 天前
LeetCode——Hot 100【电话号码的字母组合】
数据结构·算法·leetcode·链表·职场和发展·贪心算法·深度优先
仰泳的熊猫1 天前
LeetCode:785. 判断二分图
数据结构·c++·算法·leetcode
微笑尅乐1 天前
中点为根——力扣108.讲有序数组转换为二叉搜索树
算法·leetcode·职场和发展
mapbar_front1 天前
面试问题—上家公司的离职原因
前端·面试
夏鹏今天学习了吗1 天前
【LeetCode热题100(46/100)】从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
吃着火锅x唱着歌1 天前
LeetCode 2389.和有限的最长子序列
算法·leetcode·职场和发展
保持低旋律节奏1 天前
C++——list链表
c++·链表·list
倔强青铜三1 天前
苦练Python第69天:subprocess模块从入门到上瘾,手把手教你驯服系统命令!
人工智能·python·面试
倔强青铜三1 天前
苦练 Python 第 68 天:并发狂飙!concurrent 模块让你 CPU 原地起飞
人工智能·python·面试
.YM.Z1 天前
数据结构——链表(二)
数据结构·链表