86. 分隔链表

导读:本篇文章讲解 86. 分隔链表,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

86. 分隔链表icon-default.png?t=LA92https://leetcode-cn.com/problems/partition-list/

难度中等476

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

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

示例 1:

86. 分隔链表

输入:head = [1,4,3,2,5,2], x = 3
输出:[1,2,2,4,3,5]

示例 2:

输入:head = [2,1], x = 2
输出:[1,2]

提示:

  • 链表中节点的数目在范围 [0, 200] 内
  • -100 <= Node.val <= 100
  • -200 <= x <= 200

通过次数123,981提交次数196,004

 

/**
 * 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) {
        ListNode first = new ListNode();
        first.next = head;
        ListNode temp = first;
        ListNode node = first;
        ListNode z;
        while(temp.next!=null && temp.next.val<x)
        {
            temp = temp.next;
        }
        System.out.println(temp.val);
        node = temp;
        while(node.next!=null)
        {
            if(node.next.val<x)
            {
                z = node.next;
                node.next = node.next.next;
                z.next = temp.next;
                temp.next = z;
                temp = temp.next;
            }
            else node = node.next;
        }
        return first.next;
    }
}

86. 分隔链表

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69110.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!