学生-简单链表

来源:互联网 发布:傻瓜式园林设计软件 编辑:程序博客网 时间:2024/06/11 16:26
#include <stdio.h>#include <stdlib.h>#include <malloc.h>struct node{    int num;    char str[20];    struct node *next;};int main(){    struct node *creat();    struct node *insert();    struct node *Delete();    void print();    struct node *head;    char str[20];    int n;    head=NULL;    head=creat(head);    print(head);    printf("\ninput insert num ,name:\n");    gets(str);    n=atoi(str);    gets(str);    head=insert(head,str,n);    print(head);    printf("\ninput delete name :\n");    gets(str);    head=Delete(head,str);    print(head);    return 0;}struct node* creat(struct node *head){    char temp[30];    struct node *p1,*p2;    p1=p2=(struct node *)malloc(sizeof(struct node));    printf("input num,name:\n");    printf("exit:double times Enter !\n");    gets(temp);    gets(p1->str);    p1->num=atoi(temp);    p1->next=NULL;    while(strlen(p1->str)>0)    {        if(head==NULL)        head=p1;        else        p2->next=p1;        p2=p1;        p1=(struct node*)malloc(sizeof(struct node));        printf("input num,name:\n");        printf("exit:double times Enter!\n");        gets(temp);        gets(p1->str);        p1->num=atoi(temp);        p1->next=NULL;    }    return head;    }struct node *insert(head ,pstr,n)struct node * head;char *pstr;int n;{    struct node *p1,*p2,*p3;   p1=(struct node*)malloc(sizeof(struct node));   strcpy(p1->str,pstr);   p1->num=n;   p2=head;   if(head==NULL)   {       head=p1;       p1->next=NULL;   }   else   {       while(n>p2->num&&p2->next!=NULL)       {           p3=p2;           p2=p2->next;       }       if(n<=p2->num)       if(head==p2)       {           p1->next=p2;           head=p1;       }       else       {           p1->next=p2;           p3->next=p1;       }       else       {p2->next=p1;       p1->next=NULL;}   }   return (head);}struct node* Delete(head,pstr)struct node *head;char *pstr;{    struct node *temp,*p;    temp=head;    if(head==NULL)     printf("\n List is NULL!");    else    {        temp=head;        while(strcmp(temp->str,pstr)!=0&&temp->next!=NULL)        {            p=temp;            temp=temp->next;        }        if(strcmp(temp->str,pstr)==0)        {            if(temp==head)            {                head=head->next;                free(temp);            }            else            {                p->next=temp->next;                printf("delete string:%s\n",temp->str);                free(temp);            }            }            else printf("\n mo find sting!\n");        }        return head;    } void print(struct node* head ) {     struct node* temp;     temp=head;     printf("\noutput string :\n");     while(temp!=NULL)     {         printf("\n%d---%s\n",temp->num,temp->str);         temp=temp->next;     }     return; }
0 0
原创粉丝点击