Foreword: Practice makes perfect! Today's practical Leetcode linked list segmentation and palindrome structure. Today’s questions all come from Niuke.com.
Practical combat one:
Idea: Let's take this linked list as an example. The end of the linked list less than 5 is inserted into the first linked list, the end of the linked list greater than 5 is inserted into the second linked list, and finally the end of the second linked list is inserted into the first linked list.
#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;
}
};
Practical combat two:
Idea: First find the middle node, then invert the middle node, compare the first node with the middle node, compare the second node with the node after the middle node, if they are equal, it is a palindrome structure, and return true , if not equal, return false. Find the intermediate node: https://editor.csdn.net/md/?articleId=134342444 You can refer to this link.
#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;
}
};
If it helps you, please support it!