資料結構-建裡連結串列-C
阿新 • • 發佈:2018-12-14
資料結構實驗之連結串列一:順序建立連結串列
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; int main() { int n, i; scanf("%d", &n); struct node *head, *tail, *p; head = (struct node *)malloc(sizeof(struct node)); tail = head; for(i = 0; i < n; i++ ) { p = (struct node *)malloc(sizeof(struct node)); scanf("%d", &p ->data); p ->next = NULL; tail ->next = p; tail = p; } p = head ->next; while(p) { if(p) printf("%d ", p ->data); else printf("%d\n", p ->data); p = p ->next; } return 0; }
資料結構實驗之連結串列二:逆序建立連結串列
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; int main() { int n, i; scanf("%d", &n); struct node *head, *p; head = (struct node *)malloc(sizeof(struct node)); head ->next = NULL; for(i = 0; i < n; i++ ) { p = (struct node *)malloc(sizeof(struct node)); scanf("%d", &p ->data); p ->next = head ->next; head ->next = p; } p = head ->next; while(p) { if(p) printf("%d ", p ->data); else printf("%d\n", p ->data); p = p ->next; } return 0; }