首页 > 技术文章 > List实现

gsblog 2013-11-26 21:22 原文

1、元素添加

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

struct ListNode{
    struct ListNode* next;
    int data;
};

typedef struct ListNode node;

void AddFront(node** head,node* newnode){
    newnode->next = *head;
    *head = newnode;
}

void PrintList(node* head)                                                                                                                                   
{
    node* cur = head;

    if(cur == NULL)
        printf("Empty List\n");
    else{

     while(cur != NULL)
        {
            if(cur->next == NULL)
                printf("%d\n", cur->data);
            else
                printf("%d->", cur->data);
            cur = cur->next;

        }
    }
}

int main()
{
    node* head = NULL;
    int data;

    int a[] = {1,2,3,4,5};
    int len = sizeof(a)/sizeof(int);
    int i;

    for(i = 0;i < len; i++ ){

        data = a[i];
        node* newnode = (node*)malloc(sizeof(node));

        newnode->data = data;
        newnode->next = NULL;
        AddFront(&head,newnode);

    }

    PrintList(head);
    return 0;
}

 

推荐阅读