插入在C

时间:2016-09-12 17:49:56

标签: c linked-list insertion-sort

我正在尝试在双向链表上执行插入排序。当用户输入“P”时,它将打印存储的已排序元素。元素存储在列表中,直到没有用尽的行,代码中的nLines表示。

我遇到了分段错误。

#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;
}

1 个答案:

答案 0 :(得分:1)

您的代码似乎希望insert函数更新currentPointer0中的main

嗯,它没有。

C使用pass by value,当函数返回时,对函数内的该值所做的任何更改都将丢失。换句话说:如果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);