目录
题型一:反转单链表
思路解析
图解如下:
OJ题实例
LeetCode
链接:206. 反转链表
解题代码
struct ListNode* reverseList(struct ListNode* head)
{
//判断链表为空的情况
if(head==NULL)
{
return NULL;
}
else
{
//反转链表
struct ListNode* n1=NULL;
struct ListNode* n2=head;
struct ListNode* n3=head->next;
while(n3)
{
n2->next=n1;
n1=n2;
n2=n3;
n3=n3->next;
}
//最后一个节点的判断
n2->next=n1;
return n2;
}
}
题型二:快慢指针
思路解析
OJ题实例
LeetCode
链接: 876. 链表的中间结点
解题代码
struct ListNode* middleNode(struct ListNode* head)
{
struct ListNode* fast=head, *slow=head;
while(fast && fast->next)
{
slow = slow -> next;
fast = fast -> next -> next;
}
return slow;
}
两类题型的结合
牛客链接: OR36 链表的回文结构
class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
if (A == NULL || A->next == NULL)
return true;
ListNode* slow, *fast, *prev, *cur, *nxt;
slow = fast = A;
//找到中间节点,即题型二快慢指针
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
prev = NULL;
//后半部分逆置,即题型一链反转
cur = slow;
while (cur)
{
nxt = cur->next;
cur->next = prev;
prev = cur;
cur = nxt;
}
//逐点比对
while (A && prev)
{
if (A->val != prev->val)
return false;
A = A->next;
prev = prev->next;
}
return true;
}
};