首页 > 解决方案 > 这里的“tempPtr”不是多余的吗?(链接列表)

问题描述

我正在练习链表,这是我们的讲师提供给我们的代码,来自 Pearson 的一本书。

struct listNode {
    char data;
    struct listNode *nextPtr;
};

typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;

...

char delete( ListNodePtr *sPtr, char value )
{
    ListNodePtr previousPtr;
    ListNodePtr currentPtr;
    ListNodePtr tempPtr;

    /* delete first node */
    if ( value == ( *sPtr )->data ) {
        tempPtr = *sPtr;
        *sPtr = ( *sPtr )->nextPtr;
        free ( tempPtr );
        return value;
    }
    else{
        previousPtr = *sPtr;
        currentPtr = ( *sPtr )->nextPtr;

        /* loop to find correct location in the list */
        while ( currentPtr != NULL && currentPtr->data != value ) {
            previousPtr = currentPtr;
            currentPtr = currentPtr->nextPtr;
        }

        /* delete node at currentPtr */
        if ( currentPtr != NULL ) {
            tempPtr = currentPtr;
            previousPtr->nextPtr = currentPtr->nextPtr;
            free ( tempPtr );
            return value;
        }       
    }

    return '\0';
}

我不明白为什么我需要使用“tempPtr”。我不能这样做:

/* delete first node */
if ( value == ( *sPtr )->data ) {
    *sPtr = ( *sPtr )->nextPtr;
    free ( *sPtr );
    return value;
}

if ( currentPtr != NULL ) {
    previousPtr->nextPtr = currentPtr->nextPtr;
    free ( currentPtr );
    return value;
}   

(传递给delete函数的是一个LinkedListPtr在中定义的对象,main并通过引用传递。它负责保存列表中第一个元素的地址。)

标签: clinked-list

解决方案


简化版:


struct listNode {
    struct listNode *next;
    char data;
   };

char delete(struct listNode  **pp, char value )
{
    struct listNode  *this;

        while ((this = *pp)) {
                if (this->data != value) { pp= &this->next; continue; }
                *pp = this->next; // this is why you need a temp pointer
                free(this);       // ::because you want to free() it
                return value;     // nonsense return
        }

    return '\0'; // nonsense return
}

以及一个测试功能的小驱动程序:


#include <stdio.h>
#include <stdlib.h>

struct listNode {
    struct listNode *next;
    char data;
   };

struct listNode *root = NULL;

void push(char val)
{
struct listNode *new;
new = malloc (sizeof *new);
new->data = val;
new->next = root;
root = new;
}

void print(struct listNode *p)
{
for (; p; p = p->next) {
        printf(" %c", p->data);
        }
printf("\n");
}

int main(void)
{
push('o');
push('l');
push('l');
push('e');
push('H');

print(root);

delete( &root, 'o');
print(root);

delete( &root, 'H'); // <<-- test if we can delete the **first** node of the chain
print(root);

return 0;
}

推荐阅读