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;
}
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;
}