• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
成长中的利剑
博客园    首页    新随笔    联系   管理    订阅  订阅

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)结束\n");
  printf("请输入菜名和价格\n");
  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\t%d\n",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("请输入你要删除的位置\n");
 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("请输入你要的功能\n");
  printf("输入按1\n输出按2\n删除按3\n插入按4\n");
  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("请继续你要的功能\n");
  }

 

posted @ 2016-12-09 16:51  成长中的利剑  阅读(401)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3