這邊使用了link list是為了能夠動態儲存使用者資料
原因在於我們不能預知使用者到底會輸入多少資料, 當然我們也可以使用c++的vector之類的東西, 只是在此並沒有使用.
而動態儲存至link list之後把它轉成array方便做sorting.
如果不曉得link list之後會介紹,在此只需要把程式碼直接copy過去即可.
其實程式真的不長,只是為了打上說明所以才變得這麼長
在此程式碼不多做說明,因為這只是事前的準備,個人在程式碼部分有打上簡單的說明,當然有些地方因個人英文不好,所以打出來的說明也許不是這麼清楚又或是文法有缺漏.
敬請多加包含.
ps:在此預設了輸入的value是integer.
#include <stdio.h> #include <stdlib.h> // structure for link list typedef struct data_node { int data; // save data struct data_node *next; // next node } data_node; // declare head and tail node pointer data_node *head, *tail; // save the data to the tail of the link list void put_to_tail(int d) { // create a node with data value d data_node *node; node = (data_node*) malloc(sizeof(data_node)); node->data = d; node->next = NULL; // no follower // if this is the first node if (head == NULL) // then this one is head and also tail head = tail = node; else { // if there are existing nodes // then put that node to the last position tail->next = node; tail = node; } } // show each elements of the link list // and return the number of the elements unsigned show_list_and_size(void) { if (head == tail) error_msg("please put in values"); // number of the elements of the link list unsigned num = 0; printf("data list is the following:\n"); // explorer of the list data_node *rush, *prev; // beginning position rush = head; // if it is not the end while (rush != NULL) { // then continue to explore // keep the previous position prev = rush; // explore the next node rush = rush->next; // print out the data printf("%d ", prev->data); // accumulate the number num++; } puts(""); // return the number of the elements return num; } // put the data from the link list to array a void list_to_arry(int *a) { data_node *rush, *prev; // beginning position rush = head; // array index start from 0 unsigned i = 0; // if it is not the end while (rush != NULL) { // then continue to explore // keep the previous position prev = rush; // put that data to the arrary a[i++] = prev->data; // explore the next node rush = rush->next; } } // print out the error message void error_msg(char *msg) { fprintf(stderr, "%s\n", msg); exit(1); } int main(void) { // initialize head and tail as NULL head = NULL; tail = NULL; printf("Enter the numbers:"); int data; // if user is still input the data, // then put it to the tail of the link list while (scanf("%d", &data) != EOF) put_to_tail(data); // show all the elements and get the size unsigned arry_size = show_list_and_size(); // allocate the arrary int *a = (int*) malloc(sizeof(int) * arry_size); // put the data from the list to that array list_to_arry(a); // allocate another array for showing the sorted result int *b = (int*) malloc(sizeof(int) * arry_size); int i; // initilize it as the original array for (i = 0; i < arry_size; ++i) b[i] = a[i]; /////////////////////////////// // func // free(a); free(b); return 0; }
沒有留言:
張貼留言