请帮我处理我的代码。我试图插入一个单独的链接列表。我的代码正在编译,但它给出了运行时错误。我无法理解我哪里出错。这是我的代码: -
#include <iostream.h>
#include <stdio.h>
using namespace std;
struct node
{
int info;
struct node* next;
};
typedef struct node* nodeptr;
void insert(nodeptr p,int x);
void print(nodeptr p);
int main()
{
nodeptr head;
head = NULL;
int num;
do
{
cout<<"ENTER A NUMBER(0 to terminate) :-\n";
cin >>num;
insert(head,num);
}
while (num != 0);
print(head);
}
void insert(nodeptr p,int x)
{
nodeptr tmp = new node;
tmp -> info = x;
tmp -> next = NULL;
nodeptr current;
current = p;
if (p == NULL)
{
p = tmp;
}
if (x < p -> info)
{
tmp->next = p;
p = tmp;
}
while((current->next != NULL) && (x >= (current->next)->info))
{
current = current -> next;
}
tmp->next = current->next;
current->next = tmp;
}
void print(nodeptr p)
{
nodeptr current;
current = p;
while(current != NULL)
{
int tmp = current->info;
cout << tmp;
current = current->next;
}
}
答案 0 :(得分:0)
首先,你从不指定任何东西,所以print(head)不会打印任何东西。
其次,在主要的最后一次是无用的。
第三
nodeptr insert(nodeptr head, int x)
{
nodeptr tmp = new node;
tmp -> info = x;
tmp -> next = NULL;
nodeptr prec = null;
nodeptr current = head;
while(current != null && x < current->info)
{
prec = current;
current = current -> next;
}
tmp->next = current;
if(prec != null)
prec->next = tmp;
else
return tmp;
return head;
}
并在主
head = insert(head, num);
在处理指针时,总是尝试将事物分开:首先寻找,然后修改。