我正在尝试使用函数在双链表的前面插入节点,但是出现了分段错误错误,只是无法理解问题所在。对于指针的类型定义,我实际上知道我不应该这样做,但是我的老师要求我对它们进行类型定义,因为谁知道原因。
这里是代码:
void insertInList(lista_char *pl){
char charSel[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'e'};
lista_char new_node = makesNode();
new_node->info = charSel[rand()%10];
new_node->next = *pl;
new_node->prev = NULL;
if(*pl != NULL)
(*pl)->prev = new_node;
*pl = new_node;
}
我认为,具有双星的指针将起作用:
#include <stdio.h>
#include <stdlib.h>
typedef struct lista_char {
char info;
struct lista_char *next;
struct lista_char *prev;
} lista_char;
lista_char *makesNode()
{
lista_char *node = malloc(sizeof(lista_char));
return (node);
}
void insertInList(lista_char **pl)
{
char charSel[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'e'};
lista_char *new_node = makesNode();
new_node->info = charSel[rand() % 10];
new_node->next = *pl;
new_node->prev = NULL;
printf("%c\n", new_node->info);
if (*pl != NULL)
(*pl)->prev = new_node;
*pl = new_node;
}
int main()
{
lista_char *temp;
lista_char *head = NULL;
for (int i = 0; i < 10; i++) {
insertInList(&head);
}
temp = head;
while (temp->next) {
if (temp->prev == NULL) {
printf("prev: %c this: %c next: %c\n", '-', temp->info, (temp->next)->info);
}
else {
printf("prev: %c this: %c next: %c\n", (temp->prev)->info, temp->info, (temp->next)->info);
}
temp = temp->next;
}
printf("%c\n", temp->info);
return 0;
}