資料結構實驗之連結串列一:順序建立連結串列(建構函式)
阿新 • • 發佈:2019-02-03
資料結構實驗之連結串列一:順序建立連結串列
Time Limit: 1000MS Memory Limit: 65536KBProblem Description
輸入N個整數,按照輸入的順序建立單鏈表儲存,並遍歷所建立的單鏈表,輸出這些資料。Input
第一行輸入整數的個數N;第二行依次輸入每個整數。
Output
輸出這組整數。Example Input
8 12 56 4 6 55 15 33 62
Example Output
12 56 4 6 55 15 33 62
Code realization
(方法二)#include <stdio.h> #include <stdlib.h> typedef struct LNode { int data; struct LNode *next; }LNode; //輸入函式 LNode *input(int n) { LNode *head, *tail, *p; head = (LNode*)malloc(sizeof(LNode)); tail = head; for(int i=0;i<n;i++) { p = (LNode*)malloc(sizeof(LNode)); scanf("%d",&p->data); tail->next = p; tail = p; tail->next = NULL; } return head; } void output(LNode *head) { LNode *p; p = head->next; while(p) { printf("%d",p->data); p = p->next; if(p) printf(" "); else printf("\n"); } } int main() { LNode *head; int n; scanf("%d",&n); head = input(n); output(head); return 0; }
#include <stdio.h> #include <stdlib.h> typedef struct LNode { int data; struct LNode *next; }LNode; //輸入函式 void input(LNode *head, LNode *tail, int n) { LNode *p; for(int i=0;i<n;i++) { p = (LNode*)malloc(sizeof(LNode)); scanf("%d",&p->data); tail->next = p; tail = p; tail->next = NULL; } } void output(LNode *head) { LNode *p; p = head->next; while(p) { printf("%d",p->data); p = p->next; if(p) printf(" "); else printf("\n"); } } int main() { LNode *head,*tail; int n; scanf("%d",&n); head = (LNode*)malloc(sizeof(LNode)); tail = head; input(head,tail,n); output(head); return 0; }