【问题标题】:ACCEPT ELEMENTS IN A LINKED LIST IN ASCENDING ORDER,but the display function prints the smallest number instead of the whole linked list以升序接受链表中的元素,但显示函数打印最小的数字而不是整个链表
【发布时间】:2018-02-26 12:14:08
【问题描述】:

按升序接受链表中的元素,然后我想打印整个链表,但它只打印第一个数字并给出运行时错误。类似的代码在 c 中的数据结构中可用。 这里 t=start 以便当输入小于起始节点的元素时,起始节点的地址保存在 t 指针中。

#include<stdio.h>
#include<stdlib.h>
//creation of a linked list
struct node 
{
int data;
struct node *next;
};
void display(struct node *start); //function to display Linked list
int main()
{
struct node *start,*t,*r;
start=NULL;
t=start;

int n,num,i;

print("\n enter the number of elements");
scanf("%d",&num);
    for(i=0;i<num;i++)
    {
        printf("\n enter the %d element",i);
    scanf("%d",&n);
    r=(struct node *)malloc(sizeof(struct node));//
    r->data=n;

    if(start==NULL || start->data>n)//if the element id the first element or the element is less than the current element
        {
        start=r;
        start->next=t;
        }
        else
        {
            t=start;
        while(t!=NULL)
        {
            if(t->data<n && (t->next==NULL || t->next->data>n))//element has to added in the end or else it should be added between the following elements
            {
                r->next=t->next;
                t->next=r;
            }
            t=t->next;
        }
        }
    }
    display(start);
}
void display(struct node *start)
{
    struct node *display;
    display=start;
    while(display!=NULL)
    {
        print("%d ",display->data);
        display=display->next;
    }
}

【问题讨论】:

  • 更多的调试器,更少的喊叫:(
  • 您能否正确格式化代码并发布您遇到的运行时错误?

标签: c sorting data-structures linked-list


【解决方案1】:

正如您的描述所暗示的,当输入的值低于列表头值时,您会遇到问题,您希望将分配的节点放在列表的开头并验证该节点现在是否指向前一个头:

if( start == NULL || start->data > n )//if the element id the first element or the element is less than the current element
{
    r->next = start; //1
    start=r; //2
    //start->next=t; //3
}
  1. 您新分配的节点r 现在应该指向下一个元素,该元素以前是您的start
  2. 现在您应该将start 指针移动到列表的头部r

你的错误:

在每个循环迭代中,t 将始终指向 NULL,因为 `t=t->next;'和'while(t!=NULL)'。

在这种情况下,每当您的 if 计算结果为 true(当前值应放在列表的开头)时,您实际上是在创建一个以该节点为头的新列表。

【讨论】:

    猜你喜欢
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    相关资源
    最近更新 更多