c语言的一个简单的链表

此程序为作业题:

但不忍丢弃成果;

所以记一下:

哦,对了,有一个易错点:在链表里,字符要用字符数组,不能用单个字符。

#include<stdio.h>
#include<stdio.h>
struct menu * head;
int n=0;
struct menu
{
 char name[10];
 int no;
 struct menu* next;
 };
 void add()
 {
  struct menu* p1,*p2;
  p1=p2=(struct menu*)malloc(sizeof(struct menu));
  head->next=p1;
  printf("按(0,0)结束 ");
  printf("请输入菜名和价格 ");
  scanf("%s%d",p2->name,&p2->no);
  while(p2->no!=0)
  {
  n=n+1;
  p1->next=p2;
  p1=p2;
  p2=(struct menu*)malloc(sizeof(struct menu));
  scanf("%s%d",p2->name,&p2->no);
  }
  p1->next=NULL;
 }
 void print()
 {
  struct menu* p1;
  p1=head->next;
  while(p1!=NULL)
  {
   printf("%s %d ",p1->name,p1->no);
   p1=p1->next;
  }
 }
 void cha_ru()
 {
  int i,a;
 struct menu *p1,*p2;
 p1=p2=(struct menu *)malloc(sizeof(struct menu));
 p1=head;
 printf("请输入你要插入的节点前的位置");
 scanf("%d",&a);
 for(i=0;i<a-1;i++)
 p1=p1->next;
 scanf("%s%d",p2->name,&p2->no);
 p2->next=p1->next;
 p1->next=p2;
}
void shanchu()
{
 int i,a;
 struct menu *p1;
 p1=(struct menu *)malloc(sizeof(struct menu));
 p1=head;
 printf("请输入你要删除的位置 ");
 scanf("%d",&a);
 for(i=0;i<a-1;i++)
 p1=p1->next;
 p1->next=p1->next->next;
}
 int main()
 {
  int a=0;
   head=(struct menu*)malloc(sizeof(struct menu));
  head->next=NULL;
  printf("请输入你要的功能 ");
  printf("输入按1 输出按2 删除按3 插入按4 ");
  while(1)
{
   scanf("%d",&a);
   switch(a)
   {
    case 1:add();break;
    case 2:print();break;
    case 3:shanchu();break;
    case 4:cha_ru();break;
   }
   if(a==' ')
   break;
    printf("请继续你要的功能 ");
  }

原文地址:https://www.cnblogs.com/maodun/p/6150233.html