我在这里用 .h 原型编写了一个双向链表的实现,一切都运行良好,直到我开始在终端中输入值。输入第二个值后出现分段错误,但是,如果我只使用 1 个值,它会正常执行。我已经经历了几次,但是,我找不到我的错误。你们能帮我找出我收到错误的原因吗?
这是.h文件:
#include <stdio.h>
typedef struct node Node;
struct node
{
int d;
Node *link;
}*head,*current,*prev;
int num_nodes;
void linked_list_init(int data);
void linked_list_sort();
void linked_list_print();
这是 .c 文件:
#include "link.h"
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
void main(){
int n,e,i;
printf("How many numbers do you want to sort: ");
scanf("%d",&e);
for(i=0;i<e;i++){
printf("Enter number: ");
scanf("%d",&n);
linked_list_init(n);
}
linked_list_sort();
printf("The sorted numbers are: ");
linked_list_print();
}
void linked_list_init(int data){
Node *prev=0,*next=0;
current=(Node*)malloc(sizeof(Node));
if(head==0)
{
head=current;
current->d=data;
current->link=0;
prev=current;
}
else{
current->d=data;
current->link=0;
prev->link=current;
prev=current;
}
}
void linked_list_sort(){
int i,j;
Node *prev=0,*next=0;
current=head;
prev=head;
next=head->link;
for(i=0;i<num_nodes-1;i++)
{
for(j=0;j<num_nodes-i-1;j++)
{
if(current->d>next->d)
{
current->link=next->link;
next->link=current;
if(current==head)
{
head=next;prev=next;
}
else
{
prev->link=next;prev=next;
}
if(next!=0) //check whether final node is reached
next=current->link;
}
else //move each node pointer by one position
{
prev=current;
current=next;
next=current->link;
}
}
//next iteration
current=head;
prev=head;
next=current->link;
}
}
void linked_list_print(){
current=head;
while(current!=0){
printf("%d ",current->d);
current=current->link;
}
}