#include <iostream>
#include <cstdio>
#include <assert.h>
typedef struct student
{
int score;
struct student *next;
}linklist;
linklist *creat (int n)
{
linklist *head ,*node ,*end;
head = (linklist*) malloc(sizeof (linklist));
end = head ;
printf("请输入第0个节点的分数\n");
scanf("%d",&(head->score));
for (int i = 1; i < n; ++i) {
node = (linklist *) malloc(sizeof(linklist));
printf("请输入第%d个节点的分数\n",i);
scanf("%d",&(node->score));
end->next = node;
end =node;
}
end->next=NULL;
return head;
}
void change(linklist *list , int n)
{
assert(n>=0);
int i = 0;
linklist *t = list;
while ( i<n && t->next!=NULL)
{
i++;
t = t->next;
}
if (i==n)
{
printf("please put the numbers you want to change\n");
scanf("%d",&(t->score));
}
else
{
printf("node isn't exit\n");
}
}
linklist * delete_node(linklist *list ,int n)
{
linklist * t =NULL;
linklist * in = list;
int i=0;
assert(n>=0);
if (n==i)
{
if (list->next!= nullptr)
{
list=list->next;
free(in);
return list;
}
else
{
free(list);
return NULL;
}
// free(list);
}
for (i = 0; i<n-1 ; i++) {
in=in->next;
}
if (in->next!= nullptr)
{
t = in->next;
in->next=t->next;
free(t);
return list;
} else
{
printf("节点不存在");
}
}
void insertlinklist(linklist *p,int n)//n表示你插入的节点是第几个节点,head为第0个 head后的node为第一个节点。
{
linklist *t,*medium;
assert(n>=0);
if (n==0){
printf("please input the value you want to insert");
scanf("%d",&(t->score));
t->next=p;
}
else if (n>0)
{
for (int i = 0; i < n && p->next!=NULL; ++i) {
p=p->next;
}
scanf("%d",&(t->score));
t->next=p->next;
p->next=t;
} else
{
printf("error");
}
}
linklist * reverse_linklist(linklist *a )
{
linklist *next= a;
linklist *pre = NULL;
while (next!= NULL)
{
next = next->next;
a->next =pre;
pre = a;
a=next;
}
return pre;
}
int main()
{
linklist *a= creat(5);
int node_index=0;
// while (a!=NULL)
// {
//// printf("第%d个节点的值是: %d\n",node_index,a->score);
// std::cout<<"第"<<node_index<<"个的分数是"<<a->score<<std::endl;
// node_index++;
// a=a->next;
// }
// change(a,4);
// a= delete_node(a,3);
a= reverse_linklist(a);
while (a!=NULL)
{
// printf("第%d个节点的值是: %d\n",node_index,a->score);
std::cout<<"第"<<node_index<<"个的分数是"<<a->score<<std::endl;//第0个就是头部节点。。。
node_index++;
a=a->next;
}
}
C++单向链表的反转
最新推荐文章于 2025-04-07 15:10:25 发布
本文介绍了如何使用C++编程实现单向链表的反转操作,包括定义链表结构、创建链表、反转链表等步骤,并提供了详细的代码示例。
306

被折叠的 条评论
为什么被折叠?



