【算法入门】利用头插法创建线性单链表(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;
}

你可能感兴趣的:(算法)