数据结构与算法课程的第18讲(线性表13),课后题
#include <stdio.h>#include <stdlib.h>
#include <time.h>
typedef struct node {
int data;
int password;
struct node* next;
} Node;
typedef Node* LinkList;
void InitList(LinkList *L);
void Sort(LinkList L);
int main(void)
{
LinkList L;
InitList(&L);
Sort(L);
return 0;
}
void InitList(LinkList *L)
{
int i;
LinkList temp, r;
*L = (LinkList)malloc(sizeof(Node));
(*L)->next = NULL;
r = *L;
for ( i=1; i<=41; i++)
{
temp = (LinkList)malloc(sizeof(Node));
if (!temp)
{
printf("内存分配失败!\n");
exit(0);
}
srand(time(0));
temp->password = rand() %100 + 1;
temp->data = i;
temp->next = *L;
r->next = temp;
r = temp;
}
temp = (*L)->next;
}
void Sort(LinkList L)
{
int n = 41;
int idx = 1;
int i;
int m; // 存储 password
LinkList temp, r;
temp = (LinkList)malloc(sizeof(Node));
if (!temp)
{
printf("内存分配失败!\n");
exit(0);
}
r = (LinkList)malloc(sizeof(Node));
if (!r)
{
printf("内存分配失败!\n");
exit(0);
}
r = NULL;
temp = L->next;
free(L);
while (temp != temp->next)
{
m = temp->password;
m %= n;
for ( i=1; i < m-1; i++)
{
temp = temp->next;
}
r = temp->next;
printf("第 %d 位是:%d\n", idx++, r->data);
temp = r->next;
free(r);
}
}
数据结构与算法课程的第18讲(线性表13),课后题,上边是我写的代码,好像是循环链表的指向出了问题,但是我才疏学浅看不出来,有没有帮忙运行一下看看的。 void InitList(LinkList *L)
{
int i;
LinkList temp, r;
*L = (LinkList)malloc(sizeof(Node));
(*L)->next = NULL;
r = *L;
for ( i=1; i<=41; i++)
{
temp = (LinkList)malloc(sizeof(Node));
if (!temp)
{
printf("内存分配失败!\n");
exit(0);
}
srand(time(0));
temp->password = rand() %100 + 1;
temp->data = i;
temp->next = *L;
r->next = temp;
r = temp;
}
temp = (*L)->next; //此处没有正确把链表环形化正确操作为temp->next = (*L)->next;
}
页:
[1]