【发布时间】:2014-02-21 05:45:39
【问题描述】:
我有一个使用 DLL 的循环队列,它使用全局声明的指针。
现在的问题是它没有被正确初始化或被清除,因此我的代码没有按预期工作。
在我的代码中,您将被询问您希望输入多少个节点“我现在设为默认值 2”,然后您可以添加或删除节点。仅添加现在有效,因为删除仍在进行中。
当您添加节点“默认为 2 个节点”时,程序将仅记录最新输入,因此如果我输入 1 和 2,则只会显示 2。我知道这可能是因为我的 *first and *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;
}
【问题讨论】:
标签: c pointers linked-list queue doubly-linked-list