c语言链表结构实现线性表的增删改查

#include<stdio.h> #include<malloc.h>

typedef struct LNode

{  

int data;  

struct LNode *next;

};

LNode *Init_LNode()

{  

LNode *head;  

head=(LNode *)malloc(sizeof(LNode));

 head->next=NULL;  return (head);

}

LNode *Create_LNode(LNode *head)

{//尾插创建  

LNode *newp,*p;

 int a;  p=head;

 printf("请输入链表数据a:\n");

 scanf("%d",&a);

 while(a!=-1)

{   

newp=(LNode *)malloc(sizeof(LNode));   

newp->data=a;  

 newp->next=NULL;   

p->next=newp;   

p=newp;   

scanf("%d",&a);  

}

 return head;

}

LNode *Insert_LNode(LNode *head)

{//头插  LNode *newp,*q;

 int a;  printf("请输入要插入的数据:");

 scanf("%d",&a);  while(a!=-1)

{   

newp=(LNode *)malloc(sizeof(LNode));   

newp->data=a;      

newp->next=head->next;//头插   

head->next=newp;   

scanf("%d",&a);

 }  

return head;

}

LNode *delete_byValue(LNode *head)

{//按值删除  

LNode *p,*q;  

int e;

 printf("输入要删除的数:\n");

 scanf("%d",&e);  

q=head;  

p=head->next;  

while(p!=NULL&&p->data!=e)

{   

q=p;   p=p->next;    

}

 if(p==NULL)

{  

 printf("元素不存在\n");  

}  

else

{   

q->next=p->next;   free(p);  

}  

return head;

}

LNode *delete_byID(LNode *head)

{//要删除第几个元素  

LNode *p,*q;  int i=0,j;  

printf("请输入要删除的第几个元素:\n");  

scanf("%d",&j);  

q=head;

 p=head->next;

 while(p!=NULL&&i<j-1)

{   

q=p;   p=p->next;   i++;  

}

 if(p==NULL)

{  

 printf("你要删除的不存在\n");  

}  

else

{   

q->next=p->next;   free(p);  

}

 return head;

}

void print(LNode *head)

{  

LNode *p;  p=head->next;  

while(p!=NULL)

{   

printf("%d ",p->data);  

 p=p->next;  }

 printf("\n");

}

int main()

{  

LNode *head;    

head=Init_LNode();

 head=Create_LNode(head);

 print(head);    head=Insert_LNode(head);  print(head);//输出    //head=delete_value(head);  head=delete_byID(head);  print(head);        return 0;

}

猜你喜欢

转载自www.cnblogs.com/jiafeng1996/p/11267427.html