2021-04-08(数据结构单链表创建 使用)
2021-04-08 本文已影响0人
张轻舟
顺序存储 ,链式存储
数组 是顺序结构->地址是连续的
a[] a是常量
//基地址+偏移
链式结构
struct student
{
int num;
char sex;
char name[100];
};
int main()
{
struct student a[100];//不用这么写
struct student *p;
p=(struct student *)malloc(sizeof(struct student));
return 0;
}
}
链式循环
image.png
image.png
image.png
#include <stdio.h>
#include <stdlib.h>
struct student{
int num;
char sex;
char name[100];
struct student *next;
};
int main()
{
struct student *p1;
struct student *p2;
struct student *p3;
p1=(struct student *)malloc(sizeof(struct student));
p2=(struct student *)malloc(sizeof(struct student));
p3=(struct student *)malloc(sizeof(struct student));
p1->num=101;
p2->num=102;
p3->num=103;
p1->next=p2;
p2->next=p3;
printf("%d\n",p1->next->num);
return 0;
}
image.png
image.png
#include <stdio.h>
#include <stdlib.h>
struct student{
int num;
char sex;
char name[100];
struct student *next;
};
int main()
{
struct student *p1;
struct student *p2;
struct student *p3;
p1=(struct student *)malloc(sizeof(struct student));
p2=(struct student *)malloc(sizeof(struct student));
p3=(struct student *)malloc(sizeof(struct student));
p1->num=101;
p1->next=NULL;
p2->num=102;
p3->num=103;
p1->next=p2;
p2->next=p3;
for(;p1!=NULL;p1=p1->next)
{
printf("%d\t",p1->num);
}
return 0;
}
image.png
image.png
image.png
链表
前驱结点:1-2-3,1是2的直接前驱
后继结点 :1-2-3,2是1的直接后继
单向链表中,除了头结点 每个结点都有一个直接前驱,除了尾结点之外每个结点都有一个直接后继。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//////////////////全局变量///////////////////////////
typedef struct stu S;
S *head;
S *p;
struct stu
{
int num;
char sex;
char name[100];
struct stu *next;
};
/////////////////自定义函数/////////////////////////
int Add()
{
S *New;
New=(S *)malloc(sizeof(S));
printf("输入个样式:学号 性别 姓名\n");
scanf("%d",&New->num);
getchar();
scanf("%c",&New->sex);
getchar();
scanf("%s",New->name);
getchar();
New->next=NULL;
p->next=New;
p=p->next;
return 0;
}
int print()
{
printf("全部信息如下:\n");
p=head->next;//从head的下一个开始打印
while(p!=NULL)
{
printf("%d %c %s\n",p->num,p->sex,p->name);
p=p->next;
}
return 0;
}
int main()
{
head=(S *)malloc(sizeof(S));
p=(S *)malloc(sizeof(S));
//head->num=100;
//head->sex='m';
//strcpy(head->name,"zhangsan");
//head->next=NULL;
p=head;//这是一个头
printf("请输入y,回车后输入数据:\n");
while(getchar()=='y')
{
getchar();
Add();
printf("输入y继续,其他字符结束\n");
}
print();
return 0;
}
//查找
image.png