• 博客(0)
  • 资源 (1)

空空如也

c语言链表示例

#include<stdio h> #include<stdlib h> #include<malloc h> #include<string h> struct Node { char name[20]; int score; struct Node next; }; 定义一个结构体 此结构体存储学生姓名 成绩以及指向该结构体的指针 typedef struct Node ListNode; ListNode CreateList int n ; 创建链表函数 返回创建的链表的头指针 void InsertList ListNode h int i char name[] int score ; 插入结点函数 void DeleteList ListNode h int i int n ; 删除结点函数 void PrintList ListNode h ; 打印链表函数 int main { ListNode h; int i 1 n score; char name[20]; while i { printf "1 Create a new list n" ; printf "2 Add a new student"s information n" ; printf "3 Delete a student"s information n" ; printf "4 All student"s information n" ; printf "0 Quit n" ; scanf "%d" &i ; switch i { case 1: printf "Enter the number of students n n " ; scanf "%d" &n ; h CreateList n ; 创建链表 h是头指针 printf "List elements is: n" ; PrintList h ; break; case 2: printf "input the position of insert element:" ; scanf "%d" &i ; if i<1||i>n+1 控制条件 { printf "Error input n" ; break; } else { printf "input name of the student:" ; scanf "%s" name ; printf "input score of the student:" ; scanf "%d" &score ; InsertList h i name score ; printf "List elements is: n" ; PrintList h ; break; } case 3: printf "input the position of delete element:" ; scanf "%d" &i ; DeleteList h i n ; 调用删除结点函数 printf "list element is: n" ; PrintList h ; break; case 4: printf "list element is: n" ; PrintList h ; break; case 0: return; break; default: printf "illegal input " ; } } return 0; } ListNode CreateList int n { ListNode head; 定义头指针 ListNode p pre; int i; head ListNode malloc sizeof ListNode ; 给头结点分配空间 head >next NULL; 头结点的指针域为空 pre head; for i 1;i< n;i++ { printf "input name of the %d student:" i ; p ListNode malloc sizeof ListNode ; 创建一个新的结点 指针p指向它 scanf "%s" &p >name ; 给数据域赋值 printf "input score of the %d student:" i ; scanf "%d" &p >score ; 给数据域赋值 pre >next p; pre p; } p >next NULL; 最后一个结点指针域为空 return head; } void PrintList ListNode h { ListNode p; p h >next; p指向首元结点 while p { printf "%s %d" p >name p >score ; p p >next; 依次遍历 每访问完一个结点p指向下一个结点 printf " n" ; } } void InsertList ListNode h int i char name[] int e { ListNode q p; int j 0; p h; for j 0;j<i 1;j++ p指向第i 1个结点 { p p >next; } q ListNode malloc sizeof ListNode ; 创建个新结点 q指向它 strcpy q >name name ; q >score e; q >next p >next; q指向的结点的指针域指向第i个结点 p >next q; 第i 1个结点指向第i个结点 } void DeleteList ListNode h int i int n { ListNode p q; int j; char name[10]; int score; if i<1||i>n printf "illegal input n" ; else { j 0; p h; for j 0;j<i 1;j++ p指向第i 1个结点 { p p >next; } q p >next; q指向第i个结点 p >next q >next; 第i 1个结点的指针域指向第i+1个 strcpy name q >name ; score q >score; free q ; printf "name %s score %d n" name score ; 把删除的结点的数据域输出 } }">#include<stdio h> #include<stdlib h> #include<malloc h> #include<string h> struct Node { char name[20]; int score; struct Node next; }; 定义一个结构体 此结构体存储学生姓名 成绩以及指向该结构体的指针 typedef struct Node ListNode; ListN [更多]

2014-02-02

空空如也

TA创建的收藏夹 TA关注的收藏夹

TA关注的人

提示
确定要删除当前文章?
取消 删除