【发布时间】:2022-01-15 04:22:20
【问题描述】:
我编写了一个从排序数组创建列表的程序,但不知何故我的打印功能不起作用。有谁知道问题出在哪里?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
typedef struct node{struct node *prev; int data; struct node *next;} node;
node *head;
void insertion_at_beginning();
void insertion_at_end();
void bubble_sort();
void print_list();
node* array_to_list();
int main()
{
srand((long) time(NULL));
int data[200];
node *head = NULL;
for (int i=0;i<200;i++){
data[i] = rand() % (49 + 1 - 0) + 0;
}
bubble_sort(data, 200);
head = array_to_list(data, 200);
print_list(head, "LIST");
return 0;
}
void insertion_at_beginning(int d)
{
struct node *ptr;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\no v e r f l o w");
if(head==NULL)
{
ptr -> next = NULL;
ptr -> prev = NULL;
ptr -> data = d;
head = ptr;
}
else
{
ptr -> data = d;
ptr -> prev = NULL;
ptr -> next = head;
head -> prev = ptr;
head = ptr;
}
}
}
void insertion_at_end(int f)
{
struct node *ptr, *temp;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\no v e r f l o w");
}
ptr -> data = f;
if(head == NULL)
{
ptr -> next = NULL;
ptr -> prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp -> next != NULL)
{
temp = temp -> next;
}
temp -> next = ptr;
ptr -> prev = temp;
ptr -> next = NULL;
}
}
node* array_to_list(int d[], int size)
{
insertion_at_beginning(d[0]);
int i;
for(i=1; i<size; i++)
{
insertion_at_beginning(d[i]);
}
return head;
}
void bubble_sort(int array[], int size)
{
for (int i = 0 ; i < size - 1; i++)
{
for (int j = 0 ; j < size - i - 1; j++)
{
if (array[j] < array[j+1])
{
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
void print_list(node *h, char *title)
{
printf("%s\n\n", title);
while (h != NULL)
{
printf("%d : ", h -> data);
h = h -> next;
printf("%d : ", h -> data);
h = h -> next;
printf("%d : ", h -> data);
h = h -> next;
printf("%d : ", h -> data);
h = h -> next;
printf("%d : ", h -> data);
h = h -> next;
printf("\n");
}
}
因此,使用最后一个函数,我确实管理了打印单链表,并且我认为它应该以与双链表相同的方式工作。但不知何故,它只打印标题“LIST”之外的任何内容。
【问题讨论】:
-
听起来您可能需要学习如何使用调试器来单步调试您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs 和 Debugging Guide
-
拥有同名的全局和局部变量(即
head)是在自找麻烦顺便说一句 -
启用额外警告的构建,并将它们视为错误。始终在函数前向声明中包含参数!
-
您的代码无法编译:
node* head = insertion_at_beginning是一个 void 函数。请edit 并粘贴您的实际代码。 -
insertion_at_beginning 的所有代码都包含在错误案例中
标签: c list printing doubly-linked-list