很久沒有寫過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;
}