目录
1、反转链表
原题链接:剑指 Offer II 024. 反转链表 - 力扣(LeetCode) (leetcode-cn.com)
思路:创建一个新链表,将原来链表中的元素头插到新链表中。
代码如下:
struct ListNode* reverseList(struct ListNode* head){
struct ListNode *p=NULL;
struct ListNode *cur=head;
while(cur){
struct ListNode *next=cur->next;
cur->next=p;
p=cur;
cur=next;
}
return p;
}
2、回文链表
原题链接:剑指 Offer II 027. 回文链表 - 力扣(LeetCode) (leetcode-cn.com)
思路:首先定义一个快指针fast,一个慢指针slow,slow每走一一个节点,fast走两个节点,然后将slow后面节点逆置,逆置后的链表与前段未逆置链表一一比较,判断是否相同,若不同返回false,全都相同返回true。
代码如下:
//逆置链表
struct ListNode* reverse(struct ListNode* head){
struct ListNode* prev=NULL,*cur=head;
while(cur){
struct ListNode* next=cur->next;
cur->next=prev;
prev=cur;
cur=next;
}
return prev;
}
bool isPalindrome(struct ListNode* head){
struct ListNode* slow=head,*fast=head;
while(fast&&fast->next){
slow=slow->next;
fast=fast->next->next;
}
//逆置后半部分链表
struct ListNode* hui=reverse(slow);
fast=head;
while(hui&&fast){
if(fast->val!=hui->val)return false;
hui=hui->next;
fast=fast->next;
}
return true;
}
3、环形链表
原题链接:141. 环形链表 - 力扣(LeetCode) (leetcode-cn.com)
思路:若链表有环的话,如果不加其他条件限制,在遍历的过程中会一直指下去,所以元素 2 这个节点会相遇两次,所以如果某个节点遇到两次,说明链表有环。
代码如下:
bool hasCycle(struct ListNode *head) {
struct ListNode *fast=head,*slow=head;
while(fast && fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
{
return true;
}
}
return false;
}
4、复杂链表的复制
原题链接:剑指 Offer 35. 复杂链表的复制 - 力扣(LeetCode) (leetcode-cn.com)
思路:
①在原链表的每个节点后面添加一个新链表
②连接起来每个节点的random
③剪下复制的节点
代码如下:
class Solution {
public:
Node* copyRandomList(Node* head) {
struct Node *cur=head;
//创建复制的节点
while(cur){
struct Node *copy=(struct Node*)malloc(sizeof(struct Node));
copy->val=cur->val;
//插入copy节点
copy->next=cur->next;
cur->next=copy;
cur=copy->next;
}
//复制random
cur=head;
while(cur){
struct Node *copy=cur->next;
if(cur->random==NULL)
{
copy->random=NULL;
}
else{
copy->random=cur->random->next;
}
cur=copy->next;
}
//剪下复制的节点
struct Node *CopyHead=NULL,*CopyTail=NULL;
cur=head;
while(cur){
struct Node *copy=cur->next;
struct Node *next=copy->next;
if(CopyTail==NULL)
{
CopyHead=CopyTail=copy;
}
else
{
CopyTail->next=copy;
CopyTail=copy;
}
cur->next=next;
cur=next;
}
return CopyHead;
}
};
写在最后
以上就是本篇文章全部内容,作者知识水平有限,若有什么错误或者需改进之处希望大家指出,若是你有更好的代码或者其他优质好题希望能给博主留言,博主希望能在CSDN与各位一起进步,感谢大家观看!