实战提升(六)

前言: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;
    }
};

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

猜你喜欢

转载自blog.csdn.net/Lehjy/article/details/134483064