c语言 单链表简单模版

Modified on: Mon, 04 Nov 2019 23:41:01 +0800 热度: 1,313 度
#include <stdio.h>
#include <stdlib.h>

typedef struct Lnode{
    int data;
    struct Lnode* Next;
}Lnode,*List;

List init(int schema)
{
    List h=(Lnode*)malloc(sizeof(Lnode));
    h->Next=NULL;
    h->data=0;
    if(schema)
    {
        Lnode* p=h;
        int value=0;
        while(~value)
        {
            scanf("%d",&value);
            if(!~value)break;
            Lnode* q=(Lnode*)malloc(sizeof(Lnode));
            q->Next=NULL;
            q->data=value;
            p->Next=q;
            p=p->Next;
        }
    }
    return h;
}
void add(List h,int value)
{
    Lnode* q=(Lnode*)malloc(sizeof(Lnode));
    Lnode* p=h;
    q->data=value;
    q->Next=NULL;
    while(p->Next)
    {
        p=p->Next;
    }
    p->Next=q;
}

void traverse(List h)
{
    Lnode* p=h->Next;
    if(h->Next==NULL)
    {
        printf("NULL\n");
        return;
    }else
    {
        printf("%d",p->data);
        p=p->Next;
    }
    while(p)
    {
        printf(" %d",p->data);
        p=p->Next;
    }
    putchar(10);
}

int main(int argc, const char * argv[]) {
    //demo No.1
    List l=init(0);
    add(l,1);
    traverse(l);
    
    //demo No.2
    List l2=init(1);
    traverse(l2);
    
    return 0;
}

添加新评论