广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C++实现LeetCode(86.划分链表)
  • 765
分享到

C++实现LeetCode(86.划分链表)

2024-04-02 19:04:59 765人浏览 独家记忆
摘要

[LeetCode] 86.Partition List 划分链表 Given a linked list and a value x, partition it such

[LeetCode] 86.Partition List 划分链表

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.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

这道题要求我们划分链表,把所有小于给定值的节点都移到前面,大于该值的节点顺序不变,相当于一个局部排序的问题。那么可以想到的一种解法是首先找到第一个大于或等于给定值的节点,用题目中给的例子来说就是先找到4,然后再找小于3的值,每找到一个就将其取出置于4之前即可,代码如下:

解法一


class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        ListNode *dummy = new ListNode(-1);
        dummy->next = head;
        ListNode *pre = dummy, *cur = head;;
        while (pre->next && pre->next->val < x) pre = pre->next;
        cur = pre;
        while (cur->next) {
            if (cur->next->val < x) {
                ListNode *tmp = cur->next;
                cur->next = tmp->next;
                tmp->next = pre->next;
                pre->next = tmp;
                pre = pre->next;
            } else {
                cur = cur->next;
            }
        }
        return dummy->next;
    }
};

这种解法的链表变化顺序为:

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

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

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

此题还有一种解法,就是将所有小于给定值的节点取出组成一个新的链表,此时原链表中剩余的节点的值都大于或等于给定值,只要将原链表直接接在新链表后即可,代码如下:

解法二


class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        if (!head) return head;
        ListNode *dummy = new ListNode(-1);
        ListNode *newDummy = new ListNode(-1);
        dummy->next = head;
        ListNode *cur = dummy, *p = newDummy;
        while (cur->next) {
            if (cur->next->val < x) {
                p->next = cur->next;
                p = p->next;
                cur->next = cur->next->next;
                p->next = NULL;
            } else {
                cur = cur->next;
            }
        }
        p->next = dummy->next;
        return newDummy->next;
    }
};

此种解法链表变化顺序为:

Original: 1 -> 4 -> 3 -> 2 -> 5 -> 2 

New:

Original: 4 -> 3 -> 2 -> 5 -> 2 

New:   1

Original: 4 -> 3 -> 5 -> 2 

New:   1 -> 2

Original: 4 -> 3 -> 5 

New:   1 -> 2 -> 2

Original: 

New:   1 -> 2 -> 2 -> 4 -> 3 -> 5 

到此这篇关于c++实现LeetCode(86.划分链表)的文章就介绍到这了,更多相关C++实现划分链表内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: C++实现LeetCode(86.划分链表)

本文链接: https://www.lsjlt.com/news/130697.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作