用头插、尾插、按顺序插入创建一个不带头节点的链表

来源:互联网 发布:韩剧上流社会知乎 编辑:程序博客网 时间:2024/04/28 18:56
#include <stdio.h>#include <stdlib.h>#include <time.h>#define N 10typedef struct Node{int data;struct Node *next;}Node, *pNode;/*尾插法*/void create_list_rear(pNode *h){srand(time(NULL));pNode p, q;p = q = *h = (pNode)calloc(1,sizeof(Node));p->next = NULL;int count = 0;while (count!=N){++count;if (count == 1){p->data = rand()%100;printf("%d ", p->data);}else{p = (pNode)calloc(1, sizeof(Node));p->data = rand() % 100;printf("%d ",p->data);p->next = NULL;q->next = p;q = p;}}printf("\n");}/*头插法*/void create_list_front(pNode *h){pNode p;p = *h = (pNode)calloc(1,sizeof(Node));p->next = NULL;int count = 0;while (count != N){++count;if (count == 1){p->data = rand() % 100;printf("%d ", p->data);}else {p = (pNode)calloc(1,sizeof(Node));p->data = rand() % 100;printf("%d ", p->data);p->next = *h;*h = p;}}printf("\n");}/*顺序插入法*/void create_list_sequence(pNode *h){pNode p, q, r=NULL;p = q = *h = (pNode)calloc(1,sizeof(Node));p->next = NULL;int count = 0;while (count != N){++count;if (count == 1){p->data = rand()%100;printf("%d ", p->data);}else{r = (pNode)calloc(1,sizeof(Node));r->data = rand() % 100;printf("%d ", r->data);p = q = *h;while (p ->next != NULL && p->data < r->data ){q = p;p = p->next;}if (p->data >= r->data){if (p == q){r->next = *h;*h = r;}else {r->next = p;q->next = r;}}else{p->next = r;r->next = NULL;}}}printf("\n");}void printList(pNode h){while (h != NULL){printf("%d ",h->data);h = h->next;}printf("\n");}int main(){pNode List = NULL;/*尾插法*/printf("尾插法:原数列的顺序为:\n");create_list_rear(&List);printf("链表的顺序为:\n");printList(List);/*头插法*/printf("头插法:原数列的顺序为:\n");create_list_front(&List);printf("链表的顺序为:\n");printList(List);/*顺序插法*/printf("顺序插法:原数列的顺序为:\n");create_list_sequence(&List);printf("链表的顺序为:\n");printList(List);return 0;}

0 0
原创粉丝点击