建立单链表并打印链表节点值

一次性编码搞定, 建立单链表并打印链表节点值.

linklist.c


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

#define     DEBUG_PRT(fmt,arg...)    printf(fmt,##arg)

typedef struct linklist
{
    int value;
    struct linklist *next;
}Mylist_s;

Mylist_s *create_list(int number)
{
    Mylist_s *head = NULL;
    Mylist_s *p = NULL;
    Mylist_s *s= NULL;
    int i = 0;
    
    if(NULL == (head = (Mylist_s *)malloc(sizeof(Mylist_s))))
    {
        DEBUG_PRT("malloc error \n");
        exit(1);
    }
    head->value = -1;
    head->next = NULL;
    
    p = head;
    for(i=0; i<number; i++)
    {
        if(NULL == (s = (Mylist_s *)malloc(sizeof(Mylist_s))))
        {
            DEBUG_PRT("malloc error \n");
            exit(1);
        }
        s->value = i;
        s->next = NULL;
        p->next = s;
        p = s;
    }

    return head;
}

void print_list(Mylist_s *head)
{
    Mylist_s *p = NULL;
    p = head->next;
    while(p != NULL)
    {
        DEBUG_PRT("%d ", p->value);
        p = p->next;
    }
    DEBUG_PRT("\n");
}

void main(void)
{
    Mylist_s *head = NULL;
    head = create_list(10);
    print_list(head);

}


Makefile:


 BIN = /usr/bin/
 GCC = $(BIN)gcc
 CFLAG =
 INC = -I.
 LIB = -L.
 SRC = linklist.c
 TAG = linklist
 RM = /bin/rm
 CP = /bin/cp
 
 all:
     $(GCC) $(CFLAG) $(INC) $(LIB) $(SRC) -o $(TAG)
 clean:
     $(RM) -rf *.o $(TAG)


运行结果:


./linklist
0 1 2 3 4 5 6 7 8 9


你可能感兴趣的:(建立单链表并打印链表节点值)