//当头节点和链表中的节点结构不一样 #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <time.h> struct NODE { int data; struct NODE *next; } H, *head, *p, *q,*s; struct phead { char str; struct NODE *next; }; int i, j, k, n, t, m; int main() { srand(time(NULL)); //填写头节点数据 phead mhead; mhead.str = 'A'; mhead.next = NULL; //头插法创建10个节点的单链表 for (i = 0; i < 10; i++) { q = (struct NODE *)malloc(sizeof(struct NODE)); if (NULL == q) return 1; //q->data = rand() % 100;//填写0..99的随机值 q->data = i; q->next = NULL; q->next=mhead.next ; mhead.next = q; } //尾插法怎么写? //输出整个单链表 s = mhead.next; while (1) { if (NULL == s) { printf("\n"); break; } printf("%d->", s->data); s = s->next; } system("pause"); return 0; }
先找到尾巴,然后其next指向新的节点