手撸一个简单的单链表

//先手撸一个单链表
#include
#include
#include

typedef struct Table{
    int chepai;
    char *driver;
    char *id_number;
    char *start_time;
    char *leave_time;
    struct Table *next;
} T;

T * creat_head_node()
{

    T *head = malloc(sizeof(T));    //结构体指针必须在定义时赋值
    if(head == NULL)
    {
        printf("malloc fail\n");
        return -1;
        //break;
    }
    memset(head,0,sizeof(T));
    head->chepai = 0;
    head->next = NULL;
    return head;
}
void creat_new_node(T *head,int i)
{
    T * new_node = malloc(sizeof(T));
    T * p = head;

    if(new_node == NULL)
    {
        printf("malloc fail\n");
        return -1;
    }
    memset(new_node,0,sizeof(T));
    new_node->chepai = i;
    new_node->next = NULL;
    while(p->next != NULL)
    {
        p = p->next;
    }
    p->next = new_node;
}

void display(T *head)
{
    T *p = head;
    while(p->next != NULL)
    {
        printf("%d\n",p->chepai);
        p = p->next;
    }
}
int main(int argc, char **argv)
//int main()
{
    T *head = creat_head_node(); 
    int i;

    for(i=1;i<10;i++)
    {
        creat_new_node(head,i); //定义结构体必须使用指针
    }
    creat_new_node(head,1);
    display(head);
    return 0;
}

你可能感兴趣的:(C++,C,C)