C语言线性表结构的实现及基本操作
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node *next;
} Node;
Node *CreatList(DataType a[],int n)//头插法建立单链表
{
Node *s=NULL;
Node *first =(Node * )malloc (sizeof(Node));
first ->next=NULL;
for(int i=0;i<n;i++){
s=(Node*)malloc(sizeof(Node));
s->data=a[i];
s->next=first->next;first->next=s;
}
return first;
}
/*Node *CreatList2(DataType a[],int n)//尾插法建立单链表 ,与头插法二者选其中一个即可
{
return first;
}
*/
int Insert(Node *first,int i,DataType x)//插入操作,在第i个位置插入元素x
{
Node *p=first;Node *s=NULL;
int count=0;
while(p!=NULL&&count<i-1 )
{
p=p->next;
count++;
}
if(p==NULL) {
printf("插入位置错误\n"); return 0; }
else
{
s=(Node *)malloc(sizeof(Node));
s->data=x;
s->next=p->next;p->next=s;
return 1;
}
}
int Delete(Node *first,int i,DataType *ptr)//删除第i个节点
{
Node *p=first, *q=NULL;
int count=0;
while( p!=NULL&&count<i-1 )
{
p=p->next;
count++;
}
if(p==NULL||p->next==NULL) {printf("位置错误\n"); return 0;}
else
{
q=p->next;*ptr=q->data;
p->next=q->next;
free(q);
return 1;
}
}
int Get(Node *first,int i,DataType *ptr)//按位查找
{
Node *p=first->next;
int count=1;
while(p!=NULL&&count<i){
p=p->next;
count++;
}
if(p==NULL){
printf("位置错误\n");return 0;}
else
*ptr=p->data; return 1;
}
int Locate(Node *first,DataType x)//按值查找 ,返回位置序号
{
Node *p=first->next;
int count=1;
while(p!=NULL)
{
if(p->data==x) return count;
p=p->next;
count++;
}
return 0;
}
void PrintList(Node *first)//遍历单链表
{
Node *p=first->next;
while(p!=NULL){
printf("%d\t",p->data);
p=p->next;
}
}
int Length(Node *first)//求单链表的长度
{
Node *p=first->next;
int count =0;
while(p!=NULL){
p=p->next;
count++;
}
printf("%d",count);
return count;
}
int main()
{
Node *first=NULL;
int a[5]={12,24,33,56,78};
int x;
int i;
int t,k;
first=CreatList(a,5);
printf("当前线性表的数据为:\n");
PrintList(first);
printf("\n") ;
printf("你要插入的数据的顺序为:");
scanf("%d",&t);
printf("插入的数据为:");
scanf("%d",&k);
Insert(first,t,k);
printf("在第二个位置插入值为9的数 执行后数据为;\n");
PrintList(first);
printf("\n") ;
printf("长度为:");
Length(first);
printf("\n") ;
printf("请输入你要删除的第几个元素:");
scanf("%d",&i);
Delete(first ,i,&x);
printf("执行后数据为;\n");
PrintList(first);
printf("\n");
printf("请输入你要查找元素:\n");
scanf("%d",&i);
i=Locate(first,x);
if(i==1) printf("元素的位置为:%d",x);
else printf("该链表没有该元素\n");
printf("请输入你要查找的第几个元素:\n");
scanf("%d",&i);
if(Get (first,i,&x)==1) {
printf("第%d号元素为%d\n",i,x);
}
return 0;
}
****遇到一问题:运行提示:
****请求大佬指正!