不知道哪里出了问题,各位爸爸能帮忙看一下吗?
1) 创建无序整数链表函数initLink()(表元值运行时输入/随机生成, 二种方法任选其一);2) 输出链表函数
3) 释放链表所占空间函数
4)创建链表倒序函数
5)创建链表数据排序函数
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
struct intNode
{
int value;
intNode *next;
};
intNode* initLink()//生成随机链表
{
intNode *head, *tail, *p, *q;
p = (intNode*)malloc(sizeof(intNode));
srand(time(NULL));
p->value = rand()%100;
head = tail=NULL;
head = p;
p->next = tail;
for(int i = 0; i < 9; i++)
{
q = (intNode*)malloc(sizeof(intNode));
q->value = rand()%100;
q->next = p;
head = q;
p = q;
}
return head;
}
intNode *copy(intNode *head)//复制链表
{
return head;
}
intNode *copyReversed(struct intNode *head)//链表倒序
{
intNode *p, *newh, *newt, *np, *nq;
p = head;
newh = newt = NULL;
np = (intNode*)malloc(sizeof(intNode));
np->value = p->value;
np->next = newt;
p = p->next;
while(p!=NULL)
{
nq = (intNode*)malloc(sizeof(intNode));
nq->value = p->value;
nq->next = np;
newh = nq;
np = nq;
p = p->next;
}
return newh;
}
intNode *copySorted(struct intNode* head)
{
int i, max;
intNode *newh, *newt, *p, *q, *o, *np, *nq;
newh = newt = NULL;
p = o = head;
q = head->next;
while(q != NULL)
{
if(o->value < q->value)
o = q;
q = q->next;
}
np = (intNode*)malloc(sizeof(intNode));
max = np->value = o->value;
newh = np;
np->next = newt;
for(i = 0; i<9; i++)
{
p = o = head;
q = head->next;
while(q != NULL)
{
if(o->value < q->value && q->value < max)
o = q;
q = q->next;
}
max = o->value;
nq = (intNode*)malloc(sizeof(intNode));
nq->value = o->value;
nq->next = np;
newh = nq;
np = nq;
}
return head;
}
void outputLink(struct intNode *head)//输出
{
struct intNode *p = head;
while(p!=NULL)
{
printf("%4d", p->value);
p = p->next;
}
printf("\n");
}
void freeLink(struct intNode *h)//释放链表所占空间函数
{
struct intNode *p;
while (h != NULL)
{
p = h;
h = h->next;
free(p);
}
}
int main()
{
struct intNode *h[4];
int i;
h[0] = initLink();
h[1] = copy(h[0]);
h[2] = copyReversed(h[0]);
h[3] = copySorted(h[0]);
for (i = 0; i < 4; i++) {
switch (i) {
case 0: printf("The random list: \n"); break;
case 1: printf("The copy of the 1st list: \n"); break;
case 2: printf("The reversed copy of the 1st list: \n"); break;
case 3: printf("The sorted copy of the 1st list: \n"); break;
}
outputLink(h[i]);
}
for (i = 0; i < 1; i++)
freeLink(h[i]);
return 0;
}
[此贴子已经被作者于2019-12-22 20:35编辑过]