[leetcode] 86. Partition List

Description

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Example:
Input:

head = 1->4->3->2->5->2, x = 3

Output:

1->2->2->4->3->5

分析

题目的意思是:给定一个链表,一个数x,要求比x小的放在链表前面,大于等于x的放在链表后面。

  • 只需要遍历一遍就行了,slow指针指向要插向的位置,fast来寻找需要移动的结点。

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(!head) return head;
        ListNode* dummy=new ListNode(0);
        ListNode* slow=dummy;
        ListNode* fast=dummy;
        dummy->next=head;
        while(fast&&fast->next){
            if(fast->next->val>=x){
                fast=fast->next;
            }else{
                if(fast==slow){
                    fast=fast->next;
                    slow=slow->next;
                }else{
                    ListNode* temp=fast->next;
                    fast->next=temp->next;
                    temp->next=slow->next;
                    slow->next=temp;
                    slow=slow->next;
                }
                
            }
        }
        return dummy->next;
    }
};

Python实现

思路很直接,构建了2个链表,l1则是拼接的小于x的节点,l2则是拼接的大于等于x的节点,然后这里注意遍历的时候,cur为了避免形成环,需要把它设置为None,然后再跳转到下一个节点。

# 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]:
        # two pointer
        l1 = ListNode(-1)
        l2 = ListNode(-1)
        p2 = l2
        p1 = l1
        cur = head
        while cur:
            next_node = cur.next
            if cur.val<x:
                p1.next = cur
                p1 = p1.next
            else:
                p2.next = cur
                p2 = p2.next
            cur.next = None
            cur = next_node
        p1.next = l2.next
        return l1.next

参考文献

[编程题]partition-list

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值