我有一个使用 DLL 的循环队列,它使用全局声明的指针。
现在的问题是它没有正确初始化或被清除,因此我的代码没有按预期工作。
在我的代码中,系统会询问您希望输入多少个节点“我现在默认为 2 个”,之后您可以添加或删除该节点。添加现在只能工作,因为删除仍在进行中。
当您添加节点“默认为2个节点”时,程序只会记录最新的输入,因此如果我输入1和2,则只会显示2。我知道这可能是因为我的 *first 和 *last
变量没有正确初始化。
我应该如何真正使用全局指针?
我对项目文件编程也很陌生,根本不喜欢指针或链表。
任何帮助和解释将不胜感激。
main.c
void main(){
int ch, number, numdum = 0;
n *new, *ptr, *prev, *first, *last;
first = NULL;
last = NULL;
clrscr();
printf("Enter number of nodes: ");
scanf("%d", &number);
while (1){
printf("\n\n[1] Insert Node \n[2] Delete Node\n[3] Exit\n");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch (ch){
case 1:
if(number != numdum){
add_node(&first,&last);
/* display(&first, &last); */
numdum++;
}else{
printf("Number of nodes achieved!");
}
break;
case 2:
delete_node();
display();
break;
case 3:
exit(0);
default:
printf("\ninvalid choice");
}
}
}
circ.h
#ifndef CIRC_H
#define CIRC_H
struct node{
int val;
struct node *next;
struct node *prev;
};
typedef struct node n;
extern int number;
int add_node(n **first, n **last);
int delete_node();
int display();
n* create_node(int data);
#endif
添加.c
int add_node(n **first, n **last){
int info,i, number = 2;
n *new, *ptr, *t1, *t2, *prev;
t1 = *first;
t2 = *last;
printf("\nEnter the value you would like to add: ");
scanf("%d", &info);
new = create_node(info);
printf("%d",t1);
if (t1 == NULL){
printf("\nfirst\n");
t1 = t2 = new;
t1->next = t2->next = NULL;
t1->prev = t2->prev = NULL;
printf("\n\n%d\n",t1);
}else{
printf("\nsecond\n");
t2->next = new;
new->prev = t2;
t2 = new;
t2->next = t1;
t1->prev = t2;
}
if (t1 == t2 && t1 == NULL)
printf("\nlist is empty no elements to print");
else{
printf("\n%d number of nodes are there", number);
for (ptr = t1, i = 0;i < number;i++,ptr = ptr->next){
printf("\n --- %d", ptr->val);
}
}
return 1;
}
创建.c
n* create_node(int info){
n *new;
new = (n *)malloc(sizeof(n));
new->val = info;
new->next = NULL;
new->prev = NULL;
return new;
}
最佳答案
您应该添加函数来初始设置结构(在程序开始时调用)和清理(在程序结束时调用)。确保您清楚地了解结构在空时和包含节点时应该是什么样子;确保您的插入/删除/显示操作在所有情况下都能正常工作;确保您的初始化创建空结构;确保您的清理工作适用于空和非空结构。也许画一些图表会有帮助。
(我不会批评您的上述代码,它缺少清晰的整体 View )。
关于使用 DLL 的循环队列,全局声明的指针未正确初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21430810/