//頭插法創建單鏈表 #include <stdio.h> #include <malloc.h> typedef struct LNode{ int data; struct LNode *next; }Node,*LinkList; LinkList HeadInsert(LinkList &); //頭插法創建單鏈表 void output(LinkList); //遍歷輸出 int main(void){ LinkList L; HeadInsert(L); output(L); return 0; } //頭插法創建單鏈表 LinkList HeadInsert(LinkList &L){ L = (Node *)malloc(sizeof(Node)); L->next = NULL; int e; scanf("%d",&e); while(e != -1){ //輸入-1表示結束輸入 Node *s = (Node *)malloc(sizeof(Node)); s->data = e; s->next = L->next; L->next = s; scanf("%d",&e); } return L; } //遍歷輸出 void output(LinkList L){ Node *p = L->next; while(p != NULL){ printf("%d ",p->data); p = p->next; } }
//尾插法創建單鏈表 #include <stdio.h> #include <malloc.h> typedef struct LNode{ int data; struct LNode *next; }Node,*LinkList; LinkList TailInsert(LinkList &); //尾插法創建單鏈表 void output(LinkList); int main(void){ LinkList L; TailInsert(L); output(L); return 0; } LinkList TailInsert(LinkList &L){ //尾插法創建單鏈表 L = (Node *)malloc(sizeof(Node)); Node *r = L; int e; scanf("%d",&e); while(e != -1){ //輸入-1表示結束輸入 Node *s = (Node *)malloc(sizeof(Node)); s->data = e; r->next = s; r = s; scanf("%d",&e); } r->next = NULL; return L; } //遍歷輸出 void output(LinkList L){ Node *p = L->next; while(p != NULL){ printf("%d ",p->data); p = p->next; } }