由于之前看了牛客网的数据结构和算法的课程知道了左神,现在找到了这本书当作入门书做做吧,虽然书的题解都是java实现的,但好在用c++实现难度不大
第二章 链表问题
第一题:有序的环形单链表中插入新节点
直接给出时间复杂度为O(N),额外空间复杂度为O(1)的方法
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution{
public:
ListNode* insertNum(ListNode* head,int num) {
ListNode* node=new ListNode(num);
if (head==nullptr)
{
node->next=node;
return node;
}
ListNode* pre=head,*cur=head->next;
while (cur!=head)
{
if (pre->val<=num&&cur->val>=num)
{
break;
}
cur=cur->next;
}
pre->next=node;
node->next=cur;
return num>head->val?head:node;//别用node->val>cur->val
}
};
第二题:合并两个有序的单链表
直接给出时间复杂度为O(M+N),额外空间复杂度为O(1)的方法
两个指针分别指向两个链表头,哪个更小动哪个往后移
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution{
public:
ListNode* insertNum(ListNode* l1,ListNode* l2) {
if (l1==nullptr)
{
return l2;
}
if (l2==nullptr)
{
return l1;
}
ListNode* newhead=new ListNode(0);
ListNode* cur=newhead;
ListNode* a1=l1,*a2=l2;
while(a1&&a2){
if (a1->val<a2->val)
{
cur->next=a1;
a1=a1->next;
cur=cur->next;
}
else{
cur->next=a2;
a2=a2->next;
cur=cur->next;
}
}
if (a1==nullptr)
{
cur->next=a2;
}
else cur->next=a1;
return newhead->next;
}
};
第三题:按照左右半区的方式重新组合单链表
直接给出时间复杂度O(N),额外空间复杂度O(1)的方法
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution{
public:
ListNode* (ListNode* head) {
if (head->next==nullptr||head->next->next==nullptr||head->next->next->next)
{
return head;
}
ListNode* slow=head,*fast=head->next;//这里的fast初始化之前写的head->next->next,错了
while (fast->next&&fast->next->next)
{
slow=slow->next;
fast=fast->next->next;
}
ListNode* a2=slow->next,*a1=head;
while (a1->next!=slow->next&&a2->next)
{
ListNode* tmp1=a1->next,tmp2=a2->next;
a1->next=a2;
a2->next=tmp1;
a1=tmp1;
a2=tmp2;
}
a1->next=a2;
return head;
}
};
最优解:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution{
public:
ListNode* insertNum(ListNode* head) {
if (head->next==nullptr||head->next->next==nullptr||head->next->next->next)
{
return head;
}
ListNode* slow=head,*fast=head->next;//这里的fast初始化之前写的head->next->next,错了
while (fast->next&&fast->next->next)
{
slow=slow->next;
fast=fast->next->next;
}
//变成两个链表
ListNode* right=slow->next,*left=head;
slow->next=nullptr;
while (left!=nullptr)
{
ListNode* tmp=right->next;
right->next=left->next;
left->next=right;
left=right->next;
right=tmp;
}
left->next=right;
return head;
}
};