【发布时间】:2015-02-08 00:35:44
【问题描述】:
问题是每次函数addNodePos被调用head指针是NULL(在调试器中看到),它只是创建一个节点的列表,它指向自己,因为它是一个循环双向链表。它显示“列表为空。” 因为list 也是NULL,当传递给printList 函数时。一直试图理解为什么,但仍然没有结果。
这里是代码(根据SSCCE删除了多余的代码)
#include <stdio.h>
#include <stdlib.h>
struct DoubleList
{
int id;
struct DoubleList *next;
struct DoubleList *prev;
};
void addNodePos(struct DoubleList* head, int value, int position);
void printList (struct DoubleList* head);
//void clearList (struct DoubleList* head);
int main()
{
int value, position;
struct DoubleList *list = NULL;
printf("\nvalue: ");
scanf("%x", &value);
printf("position: ");
scanf("%d", &position);
addNodePos(list, value, position);
printf("\nvalue: ");
scanf("%x", &value);
printf("position: ");
scanf("%d", &position);
addNodePos(list, value, position);
printList(list);
//clearList(list);
return 0;
}
void addNodePos(struct DoubleList* head, int value, int position)
{
int i;
struct DoubleList *node;
if ( (node = malloc (sizeof(struct DoubleList))) != NULL ){
node->id=value;
if (head==NULL) {
// points to itself as it is the only node in a list
node->next=node;
node->prev=node;
head=node;
} else {
struct DoubleList *current=head;
for (i = position; i > 1; i--)
current=current->next;
// reassign pointers -- relink nodes
current->prev->next=node;
node->prev=current->prev;
node->next=current;
current->prev=node;
}
}
printf("Element has been added.\n\n");
}
void printList(struct DoubleList* head)
{
if (head==NULL)
printf("\nList is empty.\n\n");
else {
struct DoubleList *current=head;
printf("\nThe list: ");
do {
printf("%d", current->id);
current=current->next;
if(current != head)
printf("<->");
} while(current!=head);
printf("\n\n");
}
}
【问题讨论】:
标签: c pointers pass-by-value