面试题集锦_4

 一个学生的信息是:姓名,学号,性别,年龄等信息,用一个链表,把这些学生信息连在一起,给出一个age,在链表中删除年龄等于age的学生信息。

实现的代码:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 typedef struct Person{
 4     char name[20];
 5     char sex;
 6     int no;
 7     int age;
 8     Person *next;
 9 }Person,*studentlist;//现在看到typedef的作用了,真好,呵呵,一定要自己动手编程
10 
11 void createlist(studentlist &h,int n)//插入结点这里出现了问题,怎样保证插入正确,并且又为后面的插入做好铺垫
12 {
13     studentlist p,q;
14     //h为头结点
15     h=(studentlist)malloc(sizeof(Person));
16     h->next=NULL;
17     p=h;
18     for(int i=0;i<n;i++)
19     {
20       q=(studentlist)malloc(sizeof(Person));
21       p->next=q;
22       printf("请输入要插入结点的信息:\n");
23       scanf("%s %c %d %d",&q->name,&q->sex,&q->no,&q->age);
24       q->next=NULL;
25       p=q;
26     }
27     printf("链表创建成功!\n");
28 }
29 void DeleteNode(studentlist &h,int age)
30 {
31     studentlist pt=h,qt,q;
32     qt=pt;//qt前驱结点
33     pt=pt->next;
34     while(pt->age!=age)
35     {    
36         qt=pt;
37         pt=pt->next;
38     }
39     q=pt;
40     qt->next=pt->next;//删除pt这个结点
41     free(q);
42 }
43 int main()
44 {
45     studentlist h,ph,qh;
46     int n,age,i;
47     printf("输入链表的长度:\n");
48     scanf("%d",&n);
49     createlist(h,n);
50     printf("输出链表的信息:\n");
51     ph=h;
52     ph=ph->next;
53     for(i=0;i<n;i++)
54     {
55         printf("%s %c %d %d",ph->name,ph->sex,ph->no,ph->age);
56         printf("\n");
57         ph=ph->next;
58     }
59     printf("输入你要删除的结点的年龄:\n");
60     scanf("%d",&age);
61     DeleteNode(h,age);
62     printf("删除结点后链表的信息:\n");
63     qh=h;
64     qh=qh->next;
65     for(i=0;i<n;i++)
66     {
67         if(qh!=NULL)
68         {
69          printf("%s %c %d %d",qh->name,qh->sex,qh->no,qh->age);
70          printf("\n");
71          qh=qh->next;
72         }
73     }
74     //student s;
75         
76 }
View Code

总结:链表的使用,虽然已经做了那么多的练习,但是不熟练。(链表信息的输出应该写个函数的,这样写有点代码冗余)

 

posted @ 2013-06-08 20:13  wj704  阅读(175)  评论(0编辑  收藏  举报