C语言学习--链表

#include "node.h"
#include<stdio.h>
#include<stdlib.h>
//typedef struct _node {
//    int value;
//    struct _node *next;
//} Node;

int main(int agrc,char const *argv[])
{
    int number;
    Node * head = NULL;        
    do {        
        scanf("%d",&number);
        if (number != -1) {
            //add to link list
            Node *p = (Node*)malloc(sizeof(Node));
            p->value = number;
            p->next = NULL;
            //finde the last
            Node *last = head;
            if (last) {
                while (last->next) {
                last = last->next;
                }
                last->next = p;
            } else {
                head = p;
            }
        }        
    }while (number != -1);
    return 0;
}

加入LIST后

#include "node.h"
#include<stdio.h>
#include<stdlib.h>
//typedef struct _node {
//    int value;
//    struct _node *next;
//} Node;
typedef struct _list {
    Node* head;
} List;

void add(List* pList,int number);
int main(int argc,char const *argv[])
{
    int number;
    List list;
    list.head = NULL;
    do {
        scanf("%d",&number);
        add(&list,number);
    } while (number != -1);
    
    return 0;
}

void add(List* pList,int number)
{
    while (number != -1) {
            //add to link-list
            Node *p = (Node*)malloc(sizeof(Node));
            p->value = number;
            p->next = NULL;                
        // find the last
        Node *last = pList->head;
        if (last) {        
            while (last->next) {
                //attach
                last = last->next;
            }
            last->next = p;
        } else {
            pList->head = p;
        }    
        }    
}

 

posted @ 2015-04-04 13:26  sunlit  阅读(223)  评论(0编辑  收藏  举报