【Leetcode】Leetcode86.分隔链表

Leetcode86.分隔链表

题目

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

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

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list

思路

开两个指针,分别保存左边和右边的链表,然后把两个链表接一起即可。需要注意的是,要在最后把右边链表的next置为None,因为可能会有野节点的出现。比如输入是1->2->3->4->1,3。右边节点是3->4->1这肯定不对的。

代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def partition(self, head: ListNode, x: int) -> ListNode:
        left = ListNode(None)
        right = ListNode(None)
        tmp = right
        ans = left
        while(head):
            if(head.val < x):
                left.next = head
                left = left.next
            else:
                right.next = head
                right = right.next
            head = head.next
        right.next = None
        left.next = tmp.next
        return ans.next
发布了97 篇原创文章 · 获赞 55 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/voidfaceless/article/details/103356066