头歌作业2025数据结构实验二:链表
【代码】头歌作业2025数据结构实验二:链表。
·
第1关:单链表逆置
#include <iostream>
#include<vector>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode, *LinkList;
void ListReverse(LinkList &L)
{
//在此处填入代码
vector<int>v;
LinkList head=L;
LNode* cur=head->next;
while(cur)
{
v.push_back(cur->data);
cur=cur->next;
}
cur=head->next;int cnt=0;int n=v.size();
while(cur)
{
cur->data=v[n-++cnt];
cur=cur->next;
}
}
第2关:链表的倒数第k个结点
#include <iostream>
#include<vector>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode, *LinkList;
LNode* Last_kth_node(LinkList &L,int k)
{
//返回链表中倒数第k个结点的指针
//在此处填入代码
vector<LNode*>v;
LNode* cur=L->next;
while(cur)
{
v.push_back(cur);
cur=cur->next;
}
int n=v.size();
int ret=n-k;
if(ret>=0)return v[ret];
return nullptr;
}
第3关:回文链表
#include <iostream>
#include<vector>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode, *LinkList;
int isPalindrome(LinkList L)
{
//在此处填入代码
vector<int>v;
LNode* cur=L->next;
while(cur)
{
v.push_back(cur->data);
cur=cur->next;
}
int n=v.size();
for(int i=0;i<n/2;i++)
{
if(v[i]!=v[n-1-i])return 0;
}
return 1;
}
第4关:环形链表
#include <iostream>
#include<unordered_set>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode, *LinkList;
LNode * detectCycle(LinkList L)
{
//在此处填入代码
unordered_set<LNode*>set;
LNode* cur=L->next;
while(cur)
{
if(set.count(cur))return cur;
set.insert(cur);
cur=cur->next;
}
return nullptr;
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)