顺便练习下数据结构,今天的题目是:无头结点的,单链表尾插法。

   以下是main.c:

#include "main.h"
int main(int argc, char *argv[])
{
    List *head = NULL;
    int v1 = 5;
    int v2 = 6;
    head = list_create();
    list_insert( &head, v1 );
    list_insert( &head, v2 );
    list_print( head );
    list_destory( head );
    return 0;
}

以下是main.h:

#ifndef __MAIL_H__
#define __MAIL_H__
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
#endif

以下是list.c:



#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "list.h"
List *list_create()
{
    List *head;
    head = (List *)malloc(sizeof(List));
    if (head)
    {
            head->data = 2;
            head->next = NULL;
            return head;
    }
    return NULL;
}
int list_insert( List **head, int data )
{
    List *tmp = *head, *p;
    List *v1;
    if(tmp == NULL)
    {
            v1 = (List *)malloc(sizeof(List));
            if(v1)
            {
                v1->data = data;
                v1->next = NULL;
                tmp->next = v1;
                printf("tmp->data = %d\n", tmp->data);
            }
    }
    else
    {
            printf("====%d\n",tmp->data);
                               
            while(tmp->next)
            {
                tmp = tmp->next;
            }
            v1 = (List *)malloc(sizeof(List));
            if(v1)
            {
                v1->data = data;
                v1->next = NULL;
                tmp->next = v1;
            }
    }
}
void list_print(List *node)
{
    List *tmp = node;
    while(tmp)
    {
            printf("The data is [%d]\n",tmp->data);
            tmp = tmp->next;
    }
}
void list_destory(List *node)
{
    List *tmp = node;
    while( tmp )
    {
            free( tmp );
            tmp = tmp->next;
    }
}

以下是list.h:

#ifndef __LIST_h__
#define __LIST_h__
typedef struct _tag List;
struct _tag{
    int data;
    List *next;
};
int list_insert(List **head, int v1);
void list_delete(List *node);
void list_destory(List *node);
List *list_create();
void list_print(List *node);
#endif

外加一个小小的Makefile:

all:main
CFLAGS=-g
main:main.o list.o
clean:
    rm -f *.o main

OK,今天的内容就到这里了。