数据结构---单链表(建立,节点删除,节点插入)

    技术2024-08-10  66

    //UNIX环境2011-02-03


    #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct student { int num; char name[16]; struct student *next; }node; node *creat()//创建链表 { int x; int cycle = 1; char stu_name[16]; node *head,*p,*s; head =(node*)malloc(sizeof(node)); p = head; while(cycle) { printf("please input the student number:"); scanf("%d",&x); if(x != 0) { printf("please input the student name:"); scanf("%s",stu_name); // printf("STU_NAME:%s/n", stu_name); s = (node *)malloc(sizeof(node)); if(NULL == s) { exit(1); } s->num = x; memcpy(s->name, stu_name, 16); p->next = s; p = s; } else cycle = 0; } head = head->next; p->next = NULL; return head; } int length(node *head)//链表测长 { int n = 0; node *p; p = head; while(p != NULL) { n++; p = p->next; } return (n); } node *insert(node *head, int num, int length)//链表插入,NUM表示在第几个位置插入 { int n=num; int i = 1; node *p0,*p1,*p2; p1 = head; p0 = (node *)malloc(sizeof(node)); printf("please input the student number:"); scanf("%d", &p0->num); printf("please input the student name:"); scanf("%s", &p0->name); if(n == 1)//插入表头 { p0->next = p1; head = p0; return (head); } while(i < n-1)//找到要插入的前置节点 { p1 = p1->next; i++; } p2 = p1->next; p1->next = p0; p0->next = p2; if(n == length+1)//插入表尾 { p1->next = p0; p0->next = NULL; } return (head); } node *delete(node *head, int location, int length)//删除链表节点 { int n = location; int i = 1; node *p1,*p2; p1 = head; if(n == 1) { head = p1->next; free(p1); return (head); } while(i < n-1)//找到要删除的节点的前置节点 { p1 = p1->next; i++; } if(n < length) { p2 = p1->next; p1->next = p2->next; free(p2); } if(n == length) { p2 = p1->next; p1->next = NULL; free(p2); } return (head); } void print(node *head) { while(head != NULL) { printf("students:%d/n", head->num); printf("student name: %s/n", head->name); head = head->next; } } node *invert(node *head)//链表逆置 { node *p1,*p2,*p3; p1 = head; p2 = p1->next; while(p2) { p3 = p2->next; p2->next = p1; p1=p2; p2=p3; } head->next = NULL; head = p1; return (head); } int main(int argc, char **argv) { int len,insert_num,del_num; node *stu_node; stu_node = creat(); print(stu_node); len = length(stu_node); printf("there are %d node/n", len); printf("what dou you want to do?/n[a]打印链表 [b]逆置链表 [c]删除节点 [d]插入节点: "); char ch,c; c = getchar();//用于清除缓冲区中的/n字符 scanf("%c",&ch); switch (ch) { case 'a': print(stu_node); break; case 'b': stu_node = invert(stu_node); print(stu_node); break; case 'c': printf("which node dou you want to detele?:"); scanf("%d", &del_num); stu_node = delete(stu_node, del_num, len); print(stu_node); break; case 'd': printf("which location dou you want to insert:"); scanf("%d",&insert_num); stu_node = insert(stu_node , insert_num, len); print(stu_node); break; } return 0; }  

    最新回复(0)