【发布时间】: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