【问题标题】:Simple linked list with random values具有随机值的简单链表
【发布时间】:2012-12-12 19:41:00
【问题描述】:

好的,任务如下:实现一个包含 25 个 0 到 100 之间的有序随机整数的列表。

我的方法:在一个数组中获取 25 个数字,对数组进行排序并使用数组元素创建列表。

#include <conio.h>
#include <malloc.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

struct Node{
    int data;
    struct Node *next;
};

int main()
{
    struct Node *p=NULL;
    struct Node *q=NULL;
    int j,i,aux,n,v[25];

    for (i=0;i<25;i++)
    {
        v[i]=rand()%100;
    }

    for (i=0;i<25;i++)
    {
        for (j=1;j<25;j++)
        {
            if (v[i]>v[j])
            {
                aux=v[i];
                v[i]=v[j];
                v[j]=v[i];
            }
        }
    }

    q=(Node *)malloc(sizeof(struct Node));

    q->data=v[0];
    q->next=NULL;

    for (i=1;i<25;i++)
    {
        p=(Node *)malloc(sizeof(struct Node));
        q->next=p;
        p->data=v[i];
        p->next=NULL;
        q=p;
    }

    while (p)
    {
        printf("%d ",p->data);
        p=p->next;
    }

}

输出:0。

你们能弄清楚我做错了什么吗?

【问题讨论】:

  • 你没有为 rand() 播种,并且你没有从 main() 返回值,并且你正在对 malloc() 的结果进行类型转换...
  • 你也没有使用aux=v[i]。您在排序循环中设置v[i]=v[j],然后设置v[j]=v[i]。您应该设置v[j]=aux 以完成气泡交换。
  • @Mike,不播种 rand() 意味着它将默认为种子值 1。因此,他每次运行程序都会得到相同的结果。
  • 在调试器中使用单步执行程序怎么样?
  • @StarPilot - 是的......当你想要"a list random integers"时,IMO就是个问题。

标签: c list linked-list


【解决方案1】:

有很多错误...但主要的错误(导致全为 0)在这里:

        if (v[i]>v[j])
        {
            aux=v[i];
            v[i]=v[j];
            v[j]=v[i];
        }

您的交换不正确,您将v[i] 的数据存储在aux 中,但您从未将其设置为v[j],因此您只是用最小值覆盖所有内容(0

你想要的:

v[j] = aux;

另一个主要问题是您没有跟踪列表的“头部”:

    p=(struct Node *)malloc(sizeof(struct Node));
    q->next=p;
    p->data=v[i];
    p->next=NULL;
    q=p;

你不断地为p 分配一个新值,然后用p 覆盖q...所以你没有办法找到回去的路。您将只有链接列表中的最后一个值

类似:

struct Node* head = NULL;
...
head = q=(Node *)malloc(sizeof(struct Node)); // head points to the first node now

然后:

p = head; // reset p to the start of the list.
while (p)
{
    ...

【讨论】:

  • 我应该怎么做才能跟踪head
  • @DanPasca - 查看编辑。它只是一个不会移动的指针。它指向您分配的第一个节点,然后每当您想回到列表的开头时,您就将自己设置为 head。
【解决方案2】:

你不需要设置所有这些数组的东西;下面的片段返回带有随机负载的 N=cnt 节点的链表:

struct Node *getnrandom(unsigned cnt) {
struct Node *p=NULL, **pp;

for (pp=&p; cnt--; pp = &(*pp)->next) {
    *pp = malloc (sizeof **pp);
    if (!*pp) break;
    (*pp)->data = rand();
    }
if (*pp) (*pp)->next = NULL;
return p;
}

更新:由于 OP 似乎需要对值进行排序,他可以执行插入(在正确的位置)到 llist (N*N) 中,或者对其进行事后排序。 (NlogN)

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 2017-04-17
    • 2014-01-10
    相关资源
    最近更新 更多