C語言建立連結串列程式

2019-10-16 22:08:27

建立連結串列範例程式,將以下程式碼儲存到一個原始檔中:simple_linked_list_program.c, 如下所示 -

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

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

struct node *head = NULL;
struct node *tail = NULL;
struct node *current = NULL;

//display the list
void printList() {

    struct node *ptr = head;

    printf("[head] =>\n");
    //start from the beginning
    while (ptr != NULL) {
        printf(" %d =>", ptr->data);
        ptr = ptr->next;
    }

    printf(" \n[null]\n");
}


// 將新節點插入到第一個位置
void insert(int data) {
    //create a link
    struct node *link = (struct node*) malloc(sizeof(struct node));

    //link->key = key;
    link->data = data;

    //point it to old first node
    link->next = head;

    //point first to new first node
    head = link;
}



int main() {

    insert(10);
    insert(20);
    insert(30);
    insert(40);
    insert(50);
    insert(60);

    printList();
    return 0;
}

執行上面程式,得到以下結果 -

[head] =>
 60 => 50 => 40 => 30 => 20 => 10 =>
[null]