【问题标题】:why doesn't my sorted code work in c? [closed]为什么我的排序代码在 c 中不起作用? [关闭]
【发布时间】:2014-07-05 22:17:22
【问题描述】:

这是我的代码。它不起作用:

void insertioon (int d)   // this part, insert and sort list
{                     
    struct node *np, *temp, *prev;
    int found;

    np=malloc(sizeof(struct node));
    np->data = d;
    np->nextPtr = NULL;

    temp=firstPtr;
    found=0;
    while ((temp != NULL) && !found)
    {

        if (temp->data <d)
        {
            prev = temp;
            temp = temp->nextPtr;
        }
        else
        {
            found=1;
        }

        if (prev == NULL)
        {
            np->nextPtr=firstPtr;
            firstPtr=np;
        }
        else
        {
            prev->nextPtr = np;
            np->nextPtr = temp;
        }
    }
}

我的错误是什么?在 insertionon 中,我想对这个列表进行排序。

【问题讨论】:

  • while循环中的插入操作。和prev取消初始化。
  • @BLUEPIXY 但我写的是 prev = temp;我初始化 prev
  • 进入循环前必须初始化为NULL。
  • 是的,但是你还要测试是否prev == NULL。为此,您必须将 prev 初始化为 NULL
  • @BLUEPIXY 好的,我用 return node 更改了我的 insertSorted 方法。现在它工作正常:D 非常感谢您

标签: c list insert sorted


【解决方案1】:
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *nextPtr;
};

struct node *firstPtr = NULL;

void insertioon (int d){
    struct node *np, *temp, *prev = NULL;
    int found;

    np=malloc(sizeof(struct node));
    np->data = d;
    np->nextPtr = NULL;

    temp=firstPtr;
    found=0;
    while ((temp != NULL) && !found)
    {

        if (temp->data <d)
        {
            prev = temp;
            temp = temp->nextPtr;
        }
        else
        {
            found=1;
        }
    }
    if (prev == NULL)
    {
        np->nextPtr=firstPtr;
        firstPtr=np;
    }
    else
    {
        prev->nextPtr = np;
        np->nextPtr = temp;
    }
}

void print_list(struct node *np){
    while(np){
        printf("%d ", np->data);
        np=np->nextPtr;
    }
}

int main(){
    insertioon(10);
    insertioon(5);
    insertioon(7);
    insertioon(1);
    insertioon(16);
    print_list(firstPtr);//1 5 7 10 16
    printf("\n");
    return 0;
}

【讨论】:

  • 非常感谢,现在可以了。我尝试使用随机 10 个数字。我希望我能做到:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-24
  • 2016-12-26
  • 1970-01-01
相关资源
最近更新 更多