主題: Ex-C4-鏈結串列(Linked list)-20150817
作者: admin 於 八月 16, 2015, 10:19:47 pm
參考課本3-8頁, 定義有一個資料欄位的結構 動態配置一個鏈結串列(Linked list) 依照資料欄位值的大小插入20個資料項
主題: 回覆: Ex-C4-鏈結串列(Linked list)-20150817
作者: admin 於 八月 16, 2015, 10:20:54 pm
#include <stdio.h> //標準輸出入函數的標頭檔 #include <stdlib.h> typedef struct node//節點結構的自定型別定義 { int data;//整數 struct node *next;//節點的指標 } Node; int main(int argc, char *argv[])//主函數入口 { Node *listA = NULL; Node *curNode = NULL; int i; srand( (unsigned) time( NULL ) );//srand()是產生亂數的種子 listA = malloc(sizeof(Node));//啟始指標指向第一個節點(node) curNode = listA; curNode->data = rand()%100; //在這個串列附加上新的資料節點 for (i=1; i<12; i++) { curNode->next = malloc(sizeof(Node));//產生新的節點 curNode = curNode->next; curNode->data = rand()%100; } curNode->next = NULL; //從第一個節點把資料印出來 curNode = listA; while ( curNode !=NULL) { printf("%2d ",curNode->data); curNode = curNode->next; } }
|