首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

C语言单链表-入门

2012-11-04 
C语言单链表--入门#include stdio.h #include malloc.h #define TRUE1#define FALSE 0/**声明一个结构

C语言单链表--入门

#include <stdio.h> #include <malloc.h> #define TRUE  1#define FALSE 0/**  声明一个结构体,名称为node*/struct node {        int no;        char name[20];        struct node * next;};/**  判定输入的编号是否已存在*/int exists (struct node * q, int no) {        while(q) {                if (q->no == no) {                        return TRUE;                }                q = q->next;        }        return FALSE;}int main(int argc, char * argv[]) {                /*定义四个结构体类型的变量*/        struct node * head = NULL;        struct node * p = NULL;        struct node * q = NULL;                /*分配内存*/        p = (struct node *)malloc(sizeof(struct node));                printf("请输入编号,输入-1表示结束:");        scanf("%d", &p->no);                while (-1 != p->no) {                printf("请输入编号 %d 处的名称:", p->no);                scanf("%s", p->name);                printf("\n");                                /**/                if (NULL == head) {                        head = p;                        q = head;                } else {                        q->next = p;                        q = p;                }                q->next = NULL;                                /**/                p = (struct node *)malloc(sizeof(struct node));                printf("请继续输入编号,输入-1表示结束:");                scanf("%d", &p->no);                                while(exists(head, p->no)) {                        printf("编号已存在,请重新输入:");                        scanf("%d", &p->no);                }        }                /*输出*/        q = head;        while(q) {                printf("no is '%d' and name is '%s'\n", q->no, q->name);                q = q->next;        }                        return 0;}


代码在“C语言网”的地址为:
http://bbs.cyuyan.com.cn/thread-5276-1-1.html

热点排行