实战提升(六)

前言:Practice makes perfect!今天实战Leetcode链表分割还有回文结构。今天的题全都来自于牛客网。

在这里插入图片描述
实战一:
在这里插入图片描述
在这里插入图片描述

思路:我们一这个链表为例,小于5的链表尾插到第一个链表,大于5的链表尾插到第二个链表,最后再将第二个链表尾插到第一个链表。

#include <cstddef>
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) {
        // write code here
        struct ListNode* head1,*head2,*tail1,*tail2;
        head1=tail1=(struct ListNode*)malloc(sizeof(struct ListNode));
        head2=tail2=(struct ListNode*)malloc(sizeof(struct ListNode));
        struct ListNode* cur=pHead;
        while(cur)
        {
            if(cur->val<x)
            {
                tail1->next=cur;
                tail1=tail1->next;
            }
            else 
            {
                tail2->next=cur;
                tail2=tail2->next;
            }
            cur=cur->next;
            
        }
        tail1->next=head2->next;
        tail2->next=NULL;
        pHead=head1->next;
        free(head1);
        free(head2);
        return pHead;

    }
};

实战二:
在这里插入图片描述

在这里插入图片描述

思路:先找到中间节点,在由中间节点去逆置,在将第一个节点和中间节点比较,第二个节点和中间节点的后一个节点相比较,如果相等就为回文结构,返回true,如果不相等就返回false。找中间节点:https://editor.csdn.net/md/?articleId=134342444可以参考此链接。

#include <cstddef>
class PalindromeList {
public:
struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode* cur=head;
    struct ListNode* newhead=NULL;
    while(cur)
    {
     struct ListNode* next=cur->next;
     cur->next=newhead;
     newhead=cur;
     cur=next;
    }
    return newhead;
}
struct ListNode* middleNode(struct ListNode* head) {
    struct ListNode* slow=head;
    struct ListNode* fast=head;
    while(fast&&fast->next)
    {
        fast=fast->next->next;
        slow=slow->next;
    }
    return slow;
}
    bool chkPalindrome(ListNode* head) {
        // write code here
        struct ListNode* mid=middleNode(head);
        struct ListNode* rehead=reverseList(mid);
        while(head&&rehead)
        {
            if(head->val!=rehead->val)
            {
                return false;
            }
            head=head->next;
            rehead=rehead->next;
        }
        return true;
    }
};

如果对你们有帮助的话,就支持一下吧!

  • 52
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 89
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 89
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Lehjy

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

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

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

打赏作者

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

抵扣说明:

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

余额充值