C語言創建鏈表程式

創建鏈表示例程式,將以下代碼保存到一個原始檔案中: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]

上一篇: C語言數學計算程式 下一篇: C語言鏈表示例程式