【算法入門】利用頭插法創建線性單鏈表(C語言實現)

很久沒有寫過C語言了,拿來練練手,其中頭指針不存儲任何數據。

#include "stdio.h"
#include "stdlib.h"

// Define the list's structure
typedef struct ListNode{
        int data;
        struct ListNode *next;
}listNode, *list;

int main(){
        listNode* newNode;
        list newList;
        int tempData=0;
        int count=0;

        newList = (list)malloc(sizeof(listNode));
        newList->next = NULL;

        while(tempData!=999){
                count++;
                scanf("%d", &tempData);
                if(count!=0 && tempData!=999){
                        newNode = (listNode*)malloc(sizeof(listNode));
                        newNode->next = newList->next;
                        newNode->data = tempData;
                        newList->next = newNode;
                }
        }

        printf("\n");
        // Print the data
        while(newList->next!=NULL){
                printf("%d\n", newList->next->data);
                newList = newList->next;
        }

        return 0;
}

不用計數器count更簡便:


#include "stdio.h"
#include "stdlib.h"

// Define the list's structure
typedef struct ListNode{
        int data;
        struct ListNode *next;
}listNode, *list;

int main(){
        listNode* newNode;
        list newList;
        int tempData=0;

        newList = (list)malloc(sizeof(listNode));
        newList->next = NULL;

        scanf("%d", &tempData);
        while(tempData!=999){
                newNode = (listNode*)malloc(sizeof(listNode));
                newNode->next = newList->next;
                newNode->data = tempData;
                newList->next = newNode;
                scanf("%d", &tempData);
        }

        printf("\n");
        // Print the data
        while(newList->next!=NULL){
                printf("%d\n", newList->next->data);
                newList = newList->next;
        }

        return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章