C language realizes the operation of linked list

#include <stdio.h>
#include <stdlib.h>
typedef struct zy
{     int num;     struct zy *next; //Pointer to structure type }yh;



int ListLength(yh *head)
{
    yh *p=head;
    int size=0;
    while(p->next!=NULL)
    {
        p=p->next;
        size++;
    }
    return size;
}

int ListInsert(yh *head,int i,int x)
{     yh *p,*q;     int j;     p=head; // p points to head node     j=-1;     while(p->next!=NULL&&j< i-1)     {         p=p->next;         j++;     }     if((q=(yh*)malloc(sizeof(yh)))==NULL)exit(1); //         Apply memory space for q     q- >num=x;     q->next=p->next;     p->next=q;     return 1; }















void TraveList(yh *head)
{
    yh *p;
    int count=0;
    p=head->next;
    while(p->next!=NULL)
    {
        count++;
        printf("%d\n",p->num);
        p=p->next;
    }
    printf("Length is %d\n",count);

}
void DeleteList(yh *head,int n)
{
    yh *p,*q;
    p=head;
    int count=0;
    while(count<n-1)
    {
        count++;
        p=p->next;
    }
    q=p->next;
    p->next=q->next;
    free(q);
    q->next=NULL;

}

void main()
{     yh *head,*q;     q=head;     if((head=(yh*)malloc(sizeof(yh)))==NULL)exit(1); //Initialize the head node, head Is a node but does not store data     head->next=NULL;     int i,x;     for(i=0;i<10;i++)     {         ListInsert(head,i,i+1);     }     //printf(" %d",head->next->next->num);     //TraveList(head);     DeleteList(head,9);     TraveList(head); }














 

Guess you like

Origin blog.csdn.net/qq_40602790/article/details/88028382