顺序表和链表的区别
链表:
- 是可以实现动态分配的存储结构;
- 存储单元是地址零散的不是连续的;
- 频繁删除和插入操作,不能随机存取;
- 线性表的长度变化大时使用。
顺序表:
- 可以随机存取;
- 存储单元地址是连续的;
- 查找操作多,少插入和删除操作;
- 线性表长度变化不大时使用。
单链表的操作
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct node
{
ElemType data;
struct node* next;
}SNode;
ElemType creatlist(SNode* L,int n) //建立线性表
{
SNode * p,* r;
int i=1;
p=L;
for(i=1;i<=n;i++)
{
r=(SNode*)malloc(sizeof(SNode));
scanf("%d",& r->data);
p->next=r;
p=r;
}
p->next=NULL;
return 0;
}
ElemType print(SNode *L) //打印线性表
{
SNode *p;
p=L->next;
while(p)
{
printf("%d",p->data);
p=p->next;
}
printf("\n");
return 0;
}
ElemType length(SNode *L) //计算线性表的长度
{
SNode *p;
int i=0;
p=L->next;
while(p)
{
i++;
p=p->next;
}
printf("%d\n",i);
return(i);
}
ElemType get(SNode *L,int i) //得到线性表第i个数据
{
int j=1;
SNode *p;
p=L->next;
if(i<1)
return(-1);
while(j<i&&p)
{
p=p->next;
j++;
}
printf("%d\n",p->data);
return 0;
}
ElemType locate(SNode *L,ElemType x) //得到x在线性表中的位置
{
int i=1;
SNode *p;
p=L->next;
while(p&&p->data!=x)
{
p=p->next;
i++;
}
printf("%d\n",i);
if (p=NULL)
return (-1);
else
return (i);
}
int insnode(SNode * L,ElemType x,int i)//在第i个节点位置插入x
{
SNode *p,*r;
int j=1;
p=L->next;
while(p&&j<i-1)
{
p=p->next;
j++;
}
if(p==NULL)
return(-1);
r=(SNode *)malloc(sizeof(SNode));
r->data=x;
r->next=p->next;
p->next=r;
return 0;
}
int delnode(SNode *L,int i) //删除第i个节点数据
{
SNode *p,*r;
int j=1;
p=L->next;
while(p&&j<i-1)
{
p=p->next;
j++;
}
r=p->next;
p->next=r->next;
printf("删除的是%d\n",r->data);
free(r);
return (r->data);
}
int main()
{
SNode L;
creatlist(&L,5);
print(&L);
length(&L);
get(&L,3);
insnode(&L,6,3);
print(&L);
delnode(&L,3);
print(&L);
return 0;
}
本文详细介绍了链表这一数据结构的特点及应用场景,并通过C语言提供了单链表的基本操作实现,包括创建、打印、获取长度等实用功能。
3044

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



