牛客网日常刷题——(CM11链表分割、OR36链表的回文结构)

  1. CM11.链表分割

题目:链表分割_牛客题霸_牛客网 (nowcoder.com)

①解决思路

方法1:分别给出两个带有哨兵位的链表,一个链表存放小于x的节点,一个存放其它的节点,最后将第二个链表链接到第一个链表的尾节点上,返回第一个链表的哨兵位的下一节点。

②代码实践

方法1
struct ListNode* partition(ListNode* pHead, int x) 
{
    struct ListNode* Lguard, *Gguard, *Ltail, *Gtail, *tail = pHead, *Ltmp, *Gtmp;
    Lguard = (struct ListNode*)malloc(sizeof(struct ListNode));
    Gguard = (struct ListNode*)malloc(sizeof(struct ListNode));
    Gguard->next = Lguard->next = nullptr;
    Ltmp = Lguard;
    Gtmp = Gguard;

    while (tail)
    {
        if (tail->val < x)
        {
            Lguard->next = tail;
            Lguard = Lguard->next;
            tail = tail->next;
        }
        else 
        {
            Gguard->next = tail;
            Gguard = Gguard->next;
            tail = tail->next;
        }
    }

    Lguard->next = Gtmp->next;
    Gguard->next = nullptr;

    return Ltmp->next;
}
  1. OR36.链表的回文结构

题目:链表的回文结构_牛客题霸_牛客网 (nowcoder.com)

①解决思路

方法1:找到链表的中间节点,并将后面一半的链表逆置,再将头结点和逆置后的头结点一一比对,直到前面的头结点为空为止。(详情请看链表中间节点(力扣日常刷题——(876、203)_轩轩曲觞阁的博客-CSDN博客)、逆置(力扣日常刷题——(206、21)_轩轩曲觞阁的博客-CSDN博客))

②代码实践

方法1
struct ListNode* middleNode(struct ListNode* head)
{
    struct ListNode* slow, *fast;
    slow = fast = head;

    while(fast && fast->next)
    {
        slow = slow->next;
        fast = fast->next->next;
    }

    return slow;
}

struct ListNode* reverseList(struct ListNode* head)
{
    if (head == NULL)
    {
        return NULL;
    }
    struct ListNode* cur = head;
    struct ListNode* newhead = NULL;


    while (cur)
    {
        struct ListNode* next = cur->next;

        //头插
        cur->next = newhead;
        newhead = cur;
        cur =next;
    }

    return newhead;
}

bool chkPalindrome(ListNode* A) 
{
    struct ListNode* Amid = middleNode(A);
    struct ListNode* revA = reverseList(Amid);
    struct ListNode* tail = A, *tmp = revA;

    while (tail->next != Amid)
    {
        if (tail->val != revA->val)
        {
            return false;
        }
        revA = revA->next;
        tail = tail->next;
    }

    return true;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值