Сортировка динамического списка - C (СИ)
Формулировка задачи:
Помогите пожалуйста.
Пишу программу для сортировки динамического списка.
Компилятор съедает, запускаю программу пишет "Ошибка сегментирования" на 188 строке.
Листинг программы
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct Config {
- int Amount;
- char Input_method[10];
- char Sorting_method[15];
- int Bottom_interval;
- int The_top_interval;
- };
- struct List {
- int info;
- struct List *next;
- };
- struct List *Create (void)
- {
- struct List *tmp;
- tmp=((struct List*)malloc(sizeof(struct List)));
- tmp -> info =0;
- tmp -> next =NULL;
- return tmp;
- }
- struct List *Addr(int Nom,struct List *Start)
- {
- struct List *tmp;
- int i;
- tmp=Start;
- for(i=1;i<Nom;i++)
- {
- tmp=tmp -> next;
- }
- return tmp ->next;
- }
- int Val(struct List *Start,int Numb)
- {
- struct List *tmp;
- tmp=Addr(Numb,Start);
- return tmp -> info;
- }
- void Append(struct List *Start,int Nam)
- {
- struct List *Last, *New_last;
- Last=Addr(Start -> info, Start);
- New_last=((struct List*)malloc(sizeof(struct List)));
- New_last -> info=Nam;
- New_last -> next =NULL;
- Last -> next=New_last;
- Start -> info++;
- }
- void Change(struct List *Start,int i,int j )
- {
- struct List *before, *Listi, *Listj;
- before=Addr(i-1,Start);
- Listi=before -> next;
- Listj=Listi -> next;
- before -> next=Listj;
- Listi -> next=Listj -> next;
- Listj -> next=Listi;
- }
- void Print(struct List *Start)
- {
- int i;
- for(i=1;i<=Start -> info;i++)
- {
- printf("%d ",Val(Start,i));
- }
- }
- void Confg_Read (FILE *fin, struct Config *Conf)
- {
- char buffer[220];
- Conf -> Amount = 10;
- strcpy(Conf -> Input_method,"rand");
- strcpy(Conf -> Sorting_method,"increase");
- Conf -> Bottom_interval = -50;
- Conf -> The_top_interval = 50;
- while (!feof(fin))
- {
- fgets(buffer,210,fin);
- if(buffer[0]!='#')
- {
- if(buffer[0]=='!'){ puts(buffer);}
- if(strstr(buffer,"Amount:"))
- {
- Conf -> Amount = atoi(strstr(buffer,"Amount:")+7);
- }
- if(strstr(buffer,"Input method:"))
- {
- strcpy(Conf -> Input_method,strstr(buffer,"Input method:")+13);
- }
- if(strstr(buffer,"Sorting method:"))
- {
- strcpy(Conf -> Sorting_method,strstr(buffer,"Sorting method:")+15);
- }
- if(strstr(buffer,"Bottom interval:"))
- {
- Conf -> Bottom_interval=atoi(strstr(buffer,"Bottom interval:")+16);
- }
- if(strstr(buffer,"The top interval:"))
- {
- Conf -> The_top_interval=atoi(strstr(buffer,"The top interval:")+17);
- }
- }
- }
- if (Conf -> Amount < 2 || Conf -> Amount > 25)
- {
- Conf -> Amount = 10;
- puts("Параметр Amount взят по умолчанию (10)");
- }
- if (strstr(Conf -> Input_method,"rand")!=NULL && strstr(Conf -> Input_method,"hand")!=NULL)
- {
- strcpy(Conf -> Input_method,"rand");
- puts("Параметр Input method Взят по умолчанию (rand)");
- }
- if (strstr(Conf -> Sorting_method,"increase")==NULL && strstr(Conf -> Sorting_method,"decrease")==NULL)
- {
- strcpy(Conf -> Sorting_method,"increase");
- puts("Параметр Sorting method Взят по умолчанию (increase)");
- }
- }
- int main(int argc,char *argv[])
- {
- FILE *fcfg;
- struct Config *Conf1;
- struct List *Start;
- char buffer[50];
- int i,j,in;
- if (argc<2)
- {
- puts("Конфиг-Файл не указан");
- exit(1);
- }
- if((fcfg=fopen(argv[1],"r"))==NULL)
- {
- puts("Не удалось открыть конфиг файл");
- exit(0);
- }
- fgets(buffer,5,fcfg);
- if (strncmp(buffer,"#CFG",4)!=0)
- {
- puts("Открытый файл не является Конфигурационным файлом для этой программы.");
- exit(0);
- }
- Start=Create();
- Conf1=((struct Config*)malloc(sizeof(struct Config)));
- Confg_Read(fcfg,Conf1);
- if(strncmp(Conf1 -> Input_method,"hand",4)==0)
- {
- for(i=1;i<=Conf1 -> Amount;i++)
- {
- printf("Введите элемент с номером %d\n",i);
- fgets(buffer,6,stdin);
- Append(Start,atoi(buffer));
- }
- }
- in=Conf1 -> The_top_interval - Conf1 -> Bottom_interval;
- if(strncmp(Conf1 -> Input_method,"hand",4)==0)
- {
- for(i=1;i<=Conf1 -> Amount;i++)
- {
- j=(rand()%in - Conf1 -> Bottom_interval);
- Append(Start,j);
- }
- }
- puts("Введенный список:");
- Print(Start);
- if(strstr(Conf1 -> Sorting_method,"increase")==0)
- {
- p: in=0;
- for(i=1;i<=Conf1 -> Amount;i++)
- {
- if(Val(Start,i)>Val(Start,i+1))
- {
- Change(Start,i,i+1);
- in=1;
- }
- }
- if(in==1) goto p;
- }
- if(strstr(Conf1 -> Sorting_method,"decrease")==0)
- {
- T: in=0;
- for(i=1;i<=Conf1 -> Amount;i++)
- {
- if(Val(Start,i)<Val(Start,i+1))
- {
- Change(Start,i,i+1);
- in=1;
- }
- }
- if(in==1) goto T;
- }
- puts("Полученный список:");
- Print(Start);
- free(Conf1);
- return 0;
- }
Решение задачи: «Сортировка динамического списка»
textual
Листинг программы
- void Print(struct List *Start)
- {
- while (start){
- printf("%d ", start->info);
- start=start->next;
- }
- }
Объяснение кода листинга программы
В данном коде представлена функция с именем Print, которая принимает в качестве аргумента указатель на начало списка (struct List *Start). Внутри функции используется цикл while, который выполняется до тех пор, пока указатель start не станет равным NULL.
- Начинается выполнение функции с инициализации указателя start значением, переданным в качестве аргумента.
- Внутри цикла while происходит вывод значения переменной start->info с помощью функции printf, а затем указатель start обновляется путем инкрементации на 1 и перехода к следующему элементу списка (start->next).
- Цикл продолжается до тех пор, пока не будет достигнут конец списка (т.е. значение указателя start станет равным NULL).
- Функция завершается после выполнения цикла while.
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д