gpt4 book ai didi

c - C中双向链表的插入排序

转载 作者:行者123 更新时间:2023-11-30 19:11:39 24 4
gpt4 key购买 nike

我正在尝试对双向链表执行插入排序。当用户输入“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;
}

最佳答案

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

嗯,事实并非如此。

C 使用按值传递,当函数返回时,您对该函数内的值所做的任何更改都会丢失。换句话说:如果在调用 insertcurrentPointer0 的值为 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);

关于c - C中双向链表的插入排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39455967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com