【发布时间】:2015-04-19 23:27:44
【问题描述】:
Node *orderedInsert(Node *p, int newval)
/* Allocates a new Node with data value newval
and inserts into the ordered list with
first node pointer p in such a way that the
data values in the modified list are in
nondecreasing order as the list is traversed.
*/
{
Node* current = NULL;
Node* prev = NULL;
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->next = NULL;
newNode->data = newval;
if(newNode == NULL)
printf("Could not allocate memory for new node");
current = p;
if(p == NULL){
current = newNode;
newNode->next = NULL;
newNode->data = newval;
return newNode;
}
else if(newval < p->data){
newNode->next = p;
p = newNode;
return p;
}
else{
prev = p;
current = current->next;
while(newNode->data > current->data && current != NULL){
prev = current;
current = current->next;
}
if(current == NULL){
prev->next = newNode;
newNode->next = NULL;
}
else{
newNode->next = current;
prev->next = newNode;
}
}
}
void printList(FILE *outfile, Node *p)
/* Prints the data values in the list with
first node pointer p from first to last,
with a space between successive values.
Prints a newline at the end of the list.
*/
{
Node* current = p;
while(current != NULL){
fprintf(outfile, "%d ",current->data);
current = current->next;
}
fprintf(outfile, "\n");
}
int main(int argc, char * argv[])
{
assert(argc == 3);
Node * p = NULL;
int newval, retval;
int op;
FILE *in = fopen(argv[1],"r");
assert(in != NULL);
FILE *out = fopen(argv[2],"w");
assert(out != NULL);
do {
op = fgetc(in);
} while (op != EOF && isspace(op));
while(op != EOF && op != 'q') {
switch(op) {
case 'i':
fscanf(in,"%d",&newval);
p = orderedInsert(p,newval);
printList(out,p);
printList(stdout,p);
break;
case 'c':
clearList(&p);
break;
default:
fclose(in);
fclose(out);
return 0;
}
do
op = fgetc(in);
while (op != EOF && isspace(op));
}
fclose(in);
fclose(out);
return 0;
}
我在调试代码时遇到了这个错误。我的代码中是否缺少明显的内容和/或您有任何调试此错误的提示?除了它甚至没有超过第一个列表条目(当列表为空时)之外,我只是发现自己迷失了从哪里开始。
谢谢
编辑:我已经提交了修改后的代码,现在只在输入大于列表中第一个数字时出现分段错误。
【问题讨论】:
-
第 15 行是
if(newNode = NULL),应该是:if(newNode == NULL)(比较) -
噢!不再..感谢您的帮助。我应该删除这个问题吗?我不知道该网站的正确礼仪。
-
它有 1 个赞,所以你可以保留它,我会添加答案,你可以接受,因为它很有用。干杯!
-
能否更新代码 sn-p 以包含 main 方法?
-
我也想看看
printList和clearList方法
标签: function debugging pointers linked-list segmentation-fault