C语言-链表-删除

删除的原理:改变指向地址

#include<stdio.h>
#include<stdlib.h>

struct Link
{
        int data;
        struct Link *next;
};
void printLink(struct Link *head)
{
        struct Link *p=head;
        while(p!=NULL)
        {
                printf("%d ",p->data);
                p=p->next;
        }
        putchar('\n');
        putchar('\n');
}
struct Link* deleteNode(struct Link *head,int inputdata)
{
        struct Link *p=head;
        if(p->data==inputdata)
        {
                head=head->next;
                free(p);
                puts("delete head success");
                return head;
        }
        while(p->next != NULL)
        {
                if(p->next->data==inputdata)
                {
                        p->next=p->next->next;
                        puts("delete success");
                        return head;
                }
                p=p->next;
        }
        return head;
}

int main()
{
        //struct Link l1={1,NULL};
        struct Link *p=(struct Link*)malloc(sizeof(struct Link));
        p->data=1;
        struct Link l2={2,NULL};
        struct Link l3={3,NULL};
        struct Link l4={4,NULL};
        struct Link l5={5,NULL};
        struct Link l10={10,NULL};

        struct Link *head=NULL;
        //head =&l1;

        //l1.next=&l2;
        p->next=&l2;
        l2.next=&l3;
        l3.next=&l4;
        l4.next=&l5;

        head=p;

        printf("print link table \n");
        printLink(head);

        head=deleteNode(head,2);
        printLink(head);

        head=deleteNode(head,5);
        printLink(head);

        return 0;
}