结构体嵌套链表实现——大学复健(终于会用指针的小蒟蒻)

发布时间 2023-03-30 15:05:45作者: nono_ttaa

太开心了终于会用指针喏


前置内容:
由于我太菜了甚至不知道这两个的区别所以写在这里
p->nex  //p地址所指向的地方的东西 ,p为指针
p.nex   //p这个结构体中的东西    , p为变量

那么关于这个东西怎么写呢,我们是会写数组模拟的所以的话

我们需要的无非就是一个结构体内的内容,还有一个或者两个指针,来对应它的前和后一个数据

struct mylist{
	int num;
	struct mylist *nex;
};
typedef struct mylist mylist;
mylist *head;

就像这样

于是后面的相信大家都会了,还有很多人写得比我好,我也就不浪费自己的时间了

很多没有给整个代码,于是我给一个

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>

struct mylist{
	int num;
	struct mylist *nex;
};
typedef struct mylist mylist;
mylist *head;
int n;


void lis_pushback(int x);
void showall();
void lisinit();
void lisdel();

int main(){
	srand(time(0));
	scanf("%d",&n);
	lisinit();
	for(int i=1;i<=n;i++){
		int now;
		scanf("%d",&now);
		lis_pushback(now);
		showall();
	}/*构造*/
	
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		int x,p;
		scanf("%d %d",&x,&p);
		mylist *now=malloc(sizeof(head));
		now->nex=NULL;
		now->num=x;
		lisinsert(p,now);
		showall();
	}/*插入*/
	
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		int p;
		scanf("%d",&p);
		lisdel(p);
		showall();
	} /*删除*/
}
void lis_pushback(int x){
	mylist *p=head;
	while(p->nex!=NULL){
		p=p->nex;
	}
	mylist *q=(mylist*)malloc(sizeof(head));
	q->num=x;
	p->nex=q;
	q->nex=NULL;
}
void showall(){
	mylist *p=head->nex;
	while(1){
		printf("%d ",p->num);
		if(p->nex==NULL)break;
		p=p->nex;
	}
	puts("");
}
void lisinit(){
	head=(mylist*)malloc(sizeof(head));
	head->nex=NULL;
}
void lisinsert(int pos,mylist *ins){
	int cnt=0;
	mylist *p=head;
	while(cnt<pos&&p->nex!=NULL){
		cnt++;
		p=p->nex;
	}
	if(cnt<pos){
		puts("over the lenght");
		return;
	}
	else{
		ins->nex=(p->nex);
		p->nex=ins;
	}
}
void lisdel(int pos){
	mylist *p=head;
	while(--pos){
		p=p->nex;
	}
	mylist *temp=p->nex;
	if(temp==NULL)return;
	p->nex=temp->nex;
	free(temp);
}
/*输入:
5
5 4 6 8 4
5
1 2
2 5
5 4
4 8
9 6
3
2 3 4
*/
/*输出:
5
5 4 6 8 4
5
5 4
5 4 6
5 4 6 8
5 4 6 8 4
5
1 2
5 4 1 6 8 4
2 5
5 4 1 6 8 2 4
5 4
5 4 1 6 5 8 2 4
4 8
5 4 1 6 5 8 2 4 4
9 6
5 4 1 6 5 8 9 2 4 4
3
2 3 4
5 1 6 5 8 9 2 4 4
5 1 5 8 9 2 4 4
5 1 5 9 2 4 4
*/