2016-09-12 4 views
-1

Я пытаюсь выполнить сортировку вставки по дважды связанному списку. Когда пользователь вводит «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; 
} 
+0

, где вы получите сегментации? вы использовали отладчик? отредактируйте – UmNyobe

+0

Я получал seg-ошибку, когда моя программа пыталась получить доступ к insertionSort, поскольку пыталась получить доступ к указателю NULL. Я решил проблему. Спасибо всем за помощь! –

ответ

1

Из кода, кажется, вы ожидаете, что функция insert обновить currentPointer0 в main.

Ну, это не так.

C использует пропуск по значению, и любое изменение, которое вы делаете для этого значения внутри функции, теряется при возврате функции. Другими словами: если currentPointer0 имеет значение 42, когда вы вызываете insert, оно все еще имеет значение 42, когда функция возвращается! Назначение, как currentPointer -> next = temp;, не действует, когда функция возвращается.

В вашем случае это неинициализировано, поэтому разыменование его (скорее всего) приведет к сбою.

Вы, вероятно, нужно двойные указатели:

void insert(Node** currentPointer, int element) // Notice 
{ 
    Node* temp = (Node*)malloc(sizeof(Node)); 

    if (head == NULL) 
    { 
     head = temp; 
     *currentPointer = head; // Notice 
     head -> data = element; 
     head -> previous = NULL; 
     head -> next = NULL; 
    } 

    else 
    { 
     temp -> previous = *currentPointer; // Notice 
     (*currentPointer) -> next = temp;  // Notice 
     (*currentPointer) = temp;    // Notice 
     (*currentPointer) -> data = element; // Notice 
     (*currentPointer) -> next = NULL;  // Notice 
    } 
} 

и называют это нравится:

insert(&currentPointer0,variable); 
+0

Что такое Узел **? Не могли бы вы рассказать. –

+0

Также, если я изменил функцию void insert на Node * insert и скажу ей вернуть обновленный currentPointer и вызвать функцию insert, такую ​​как currentPointer0 = insert (currentPointer0, variable); –

+0

Я получаю seg fault, когда моя программа пытается получить доступ к функции insertionSort(), но я не могу определить, почему? –

Смежные вопросы