打印后删除节点

时间:2013-12-02 02:18:30

标签: c

所以我正在尝试编写一个程序,在我构建的一组节点上执行一些不同的操作。但是,似乎每当我生成节点,然后打印它们,它们就会丢失或删除。我的代码如下:

void insertNodeAtTail(DlistRef dl, Info g){
/* insert a new node at the end of the list with value g */
    NodeRef n = initializeNode(g);
    if (dl->head == NULL){
        //Empty list case
        dl->tail = n;
        dl->head = n;
    } else {
        //Not empty list case
        n->prev = dl->tail;
        dl->tail->next = n;
        dl->tail = n;
    }
}/*insertNodeAtTail*/

void insertNodeAtHead(DlistRef dl, Info g){
/* insert a new node with value g at the beginning of the list */
NodeRef n = initializeNode(g);
if (dl->head == NULL){
    //Empty list case
    dl->head = n;
    dl->tail = n;
}else{
    //Not empty list case
    n->next = dl->head;
    dl->head->prev = n;
    dl->head = n;
}/*if+else*/
}/*insertNodeAtHead*/

void printListForward(DlistRef dl, char* title){
/* print list items in forward order starting at head */
/* title can be used to add a descriptive title for the list output */
    if (dl->head == NULL){
        printf("Empty list\n");
    } /*if*/

    while (dl->head != NULL){
        printf("%d ", dl->head->item->info);
        dl->head = dl->head->next;
    }/*while*/
}/*printListForward*

int main(){
char string[] = "myList";
DlistRef dl = initializeDlist();
int i;

for(i=0; i <= 15; i++){
    if(i%2 != 0){
        insertNodeAtTail(dl,i);
    }
}

printf("Forward: ");
printListForward(dl, string);

    insertNodeAtHead(dl, 0);
insertNodeAtTail(dl, 17);

printf("\n");

printf("Forward: ");
printListForward(dl, string);

return EXIT_SUCCESS;
}

我怀疑它在我的insertNodeAtTail函数中,我忘了链接一些东西。我的程序输出是:

转发:1 3 5 7 9 11 13 15 前锋:0 17

它应该分别在正面和背面附加0和17,使第二组转到: 前锋:0 1 3 5 7 9 11 13 15 17。

谢谢:)

1 个答案:

答案 0 :(得分:1)

问题在于列表的迭代。在printListForward函数中,您必须为迭代创建时间变量,因为当您说dl-&gt; head = dl-&gt; head-&gt; next;列表的内存引用被下一个覆盖。将头设置为null时的最后一次迭代结果。然后,当您打印列表时,您也清理列表。

请更改此功能的打印功能

void printListForward(DlistRef dl, char* title){
/* print list items in forward order starting at head */
/* title can be used to add a descriptive title for the list output */
    if (dl->head == NULL){
        printf("Empty list\n");
    } /*if*/

    NodeRef current = dl->head;
    while (dl->head != NULL){
        printf("%d ", current->item->info);
        current = current->next;
    }/*while*/
}/*printListForward*