算法leetcode|86. 分隔链表(rust重拳出击)


文章目录


86. 分隔链表:

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

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

样例 1:

复制代码
输入:
	
	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

分析:

  • 面对这道算法题目,二当家的再次陷入了沉思。
  • 直接模拟即可,题目没有特别说明对空间复杂度的要求,所以我们直接新建两个虚拟节点分别作为小于 x大于或等于 x 的链表头节点,分别对小于 x 的节点和大于或等于 x 的节点拉链表,遍历完毕后,将两个新建的链表结构再连接起来即可。
  • 新建两个节点是为了让代码结构简单,少一些判断逻辑,可以考虑一下如果不新建两个虚拟节点是否也可以完成,不过考虑考虑就好了,那样得不偿失。
  • rust处理链表相比其他语言要严肃一点,没那么自由,不过习惯就好了。

题解:

rust:

rust 复制代码
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
//   pub val: i32,
//   pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
//   #[inline]
//   fn new(val: i32) -> Self {
//     ListNode {
//       next: None,
//       val
//     }
//   }
// }
impl Solution {
    pub fn partition(mut head: Option<Box<ListNode>>, x: i32) -> Option<Box<ListNode>> {
        let (mut small_head, mut large_head) = (ListNode::new(0), ListNode::new(0));
        let (mut small, mut large) = (&mut small_head, &mut large_head);

        while let Some(mut node) = head {
            head = node.next.take();
            if node.val < x {
                small.next = Some(node);
                small = small.next.as_mut().unwrap();
            } else {
                large.next = Some(node);
                large = large.next.as_mut().unwrap();
            }
        }

        small.next = large_head.next;

        return small_head.next;
    }
}

go:

go 复制代码
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func partition(head *ListNode, x int) *ListNode {
    smallHead, largeHead := &ListNode{}, &ListNode{}
	small, large := smallHead, largeHead

	for head != nil {
		if head.Val < x {
			small.Next = head
			small = small.Next
		} else {
			large.Next = head
			large = large.Next
		}
		head = head.Next
	}

	large.Next = nil
	small.Next = largeHead.Next

	return smallHead.Next
}

c++:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode *smallHead = new ListNode(0);
        ListNode *small = smallHead;
        ListNode *largeHead = new ListNode(0);
        ListNode *large = largeHead;

        while (head != nullptr) {
            if (head->val < x) {
                small->next = head;
                small = small->next;
            } else {
                large->next = head;
                large = large->next;
            }
            head = head->next;
        }

        large->next = nullptr;
        small->next = largeHead->next;

        return smallHead->next;
    }
};

python:

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        small_head, large_head = ListNode(0), ListNode(0)
        small, large = small_head, large_head
        while head:
            if head.val < x:
                small.next = head
                small = small.next
            else:
                large.next = head
                large = large.next
            head = head.next
        large.next = None
        small.next = large_head.next
        return small_head.next

java:

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) {
        ListNode smallHead = new ListNode(0);
        ListNode small     = smallHead;
        ListNode largeHead = new ListNode(0);
        ListNode large     = largeHead;

        while (head != null) {
            if (head.val < x) {
                small.next = head;
                small = small.next;
            } else {
                large.next = head;
                large = large.next;
            }
            head = head.next;
        }

        large.next = null;
        small.next = largeHead.next;

        return smallHead.next;
    }
}

非常感谢你阅读本文~

欢迎【点赞】【收藏】【评论】三连走一波~

放弃不难,但坚持一定很酷~

希望我们大家都能每天进步一点点~

本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~


相关推荐
ClouGence36 分钟前
Oracle CDC 架构优化:从主库直连到 DataGuard 备库同步
数据库·后端·oracle
Gopher_HBo42 分钟前
Go语言学习笔记(十二)Tcp实现Rpc
后端
怕浪猫1 小时前
Electron 系列文章封面图
算法·架构·前端框架
糖拌西瓜皮1 小时前
Java开发者视角:深入理解Node.js异步编程模型
java·后端·node.js
雪隐1 小时前
个人电脑玩AI-04让5060 Ti给你打工——本地claude code编程助理
人工智能·后端
AskHarries1 小时前
Browser Tool:网页打开、点击、输入、截图和验证
后端
程序员cxuan2 小时前
分享一下我最近常用的 10 个 Codex 小技巧。
人工智能·后端·程序员
一线大码2 小时前
Smart-Doc 的简单使用
java·后端·restful
喵个咪2 小时前
技术复盘:基于 go-wind-cms 的官网+商城双业务渐进拆分实战
后端·架构·go
ZengLiangYi2 小时前
批量导入 1000 条对话的性能优化实战
javascript·后端·架构