您的位置:首页 > 其它

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

2014-06-09 16:16 411 查看
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N 10

typedef 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐