小弟我在建立单向链表时,到底错哪了,建立一个升序链表,从文件读入一批整数,就是有有关问题啊求各位大神指教
我在建立单向链表时,到底哪里错了,建立一个升序链表,从文件读入一批整数,就是有问题啊,求各位大神指教
#include <iostream>
#include <cstdio>
#include <cstdlib>
#define MAX 10
using namespace std;
struct link
{
int data;
struct link *next;
};
void assortArray(int array[],int n) //冒泡排序法又有问题了
{
for(int i = 0;i < n;i++)
{
for(int j = 1;j <n- i;j++)
{
int temp = 0;
if(array[j] < array[j-1])
{
temp = array[j];
array[j] = array[j-1];
array[j-1] = temp;
}
}
}
}
struct link *AppendNode(struct link * head,int array[],int j)
{
struct link *p=NULL,*pr = head;
p = (struct link *)malloc(sizeof(struct link));
if(pr == NULL)
{
head = p;
}
else
{
while(pr!= NULL)
{
pr = pr->next;
}
pr->next = p;
}
p->data = array[j];
p->next = NULL;
return head;
}
int main()
{
//从文件里读入一批整数,并保存在数组中
FILE *fp;
struct link * head = NULL;
int array[10];
int i = -1;
if((fp = fopen("d:\\data.txt","r")) == NULL)
{
printf("Failure to open data.txt");
exit(0);
}
while(!feof(fp))
{
i++;
fscanf(fp,"%d",&array[i]);
}
//对数组进行升序排列
assortArray(array,i);
for(int k =0;k<i;k++)
{
cout << array[k] << endl;
}
int j =0;
cout << i << endl;
//建立升序链表
while(j < i)
{
cout << j << endl;
head = AppendNode(head,array,j);
j++;
}
return 0;
}
------解决方案--------------------
建议分段定位问题,掌握必要调试技巧。定位一下是文件读取错误?还是冒泡排序错误?还是升序排列错误?代码就这么几行,你自己可以搞定它的,加油。
------解决方案--------------------
for(int i = 0;i < n;i++)
改为
for(int i = 0;i < n-1;i++)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#define MAX 10
using namespace std;
struct link
{
int data;
struct link *next;
};
void assortArray(int array[],int n) //冒泡排序法又有问题了
{
for(int i = 0;i < n;i++)
{
for(int j = 1;j <n- i;j++)
{
int temp = 0;
if(array[j] < array[j-1])
{
temp = array[j];
array[j] = array[j-1];
array[j-1] = temp;
}
}
}
}
struct link *AppendNode(struct link * head,int array[],int j)
{
struct link *p=NULL,*pr = head;
p = (struct link *)malloc(sizeof(struct link));
if(pr == NULL)
{
head = p;
}
else
{
while(pr!= NULL)
{
pr = pr->next;
}
pr->next = p;
}
p->data = array[j];
p->next = NULL;
return head;
}
int main()
{
//从文件里读入一批整数,并保存在数组中
FILE *fp;
struct link * head = NULL;
int array[10];
int i = -1;
if((fp = fopen("d:\\data.txt","r")) == NULL)
{
printf("Failure to open data.txt");
exit(0);
}
while(!feof(fp))
{
i++;
fscanf(fp,"%d",&array[i]);
}
//对数组进行升序排列
assortArray(array,i);
for(int k =0;k<i;k++)
{
cout << array[k] << endl;
}
int j =0;
cout << i << endl;
//建立升序链表
while(j < i)
{
cout << j << endl;
head = AppendNode(head,array,j);
j++;
}
return 0;
}
------解决方案--------------------
建议分段定位问题,掌握必要调试技巧。定位一下是文件读取错误?还是冒泡排序错误?还是升序排列错误?代码就这么几行,你自己可以搞定它的,加油。
------解决方案--------------------
for(int i = 0;i < n;i++)
改为
for(int i = 0;i < n-1;i++)