Я пытаюсь выполнить сортировку вставки по дважды связанному списку. Когда пользователь вводит «P», он будет печатать отсортированные элементы. Элементы хранятся в списке до тех пор, пока не будет исчерпан поток строк, который обозначается nLines в коде.Вставка Сортировка по дважды связанному списку в C
Я получаю ошибку сегментации.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node* previous;
struct Node* next;
}Node;
Node* head = {NULL};
// To insert new element into the doubly linked list
void insert(Node* currentPointer, int element)
{
Node* temp = (Node*)malloc(sizeof(Node));
if (head == NULL)
{
head = temp;
currentPointer = head;
head -> data = element;
head -> previous = NULL;
head -> next = NULL;
}
else
{
temp -> previous = currentPointer;
currentPointer -> next = temp;
currentPointer = temp;
currentPointer -> data = element;
currentPointer -> next = NULL;
}
}
//Performing insertion sort on the doubly linked list
void insertionSort(Node* currentPointer)
{
Node* temp = currentPointer;
while (temp != NULL && temp -> data < (temp -> previous) -> data)
{
int variable = temp -> data;
temp -> data = (temp -> previous) -> data;
(temp -> previous) -> data = variable;
temp = temp -> previous;
}
}
//Function to print the sorted elements
void printSorted()
{
Node* temp = head;
while(temp != NULL)
{
printf("%d ",temp -> data);
temp = temp -> next;
}
printf("\n");
}
int main()
{
int nLines;
Node* currentPointer0;
printf("Enter the no. of lines: ");
scanf("%d\n",&nLines);
while(nLines--)
{
int variable;
scanf("%d\n",&variable);
if ((char)variable == 'P')
{
printSorted();
}
else
{
insert(currentPointer0,variable);
insertionSort(currentPointer0);
}
}
//After the program is done free all the memory
while(head != NULL)
{
Node* temp = head;
head = head -> next;
free(temp);
}
return 0;
}
, где вы получите сегментации? вы использовали отладчик? отредактируйте – UmNyobe
Я получал seg-ошибку, когда моя программа пыталась получить доступ к insertionSort, поскольку пыталась получить доступ к указателю NULL. Я решил проблему. Спасибо всем за помощь! –