c - 这里的“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
并通过引用传递。它负责保存列表中第一个元素的地址。)
解决方案
简化版:
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;
}
推荐阅读
- javascript - 使用 JS ID 作为 html 中的背景图片 url
- typescript - 在 TS 中,为什么 number[][number] === number?
- python - 使用 web3.py 解码智能合约的返回值?
- c# - 如何从 Firebase unity c# 中的数据快照获取密钥?
- sql-server - 用户编辑由直通查询的结果过滤的链接 SQL Server 表
- swiftui - 如何将我的 SwiftUI 视图的 @State 交换为我的视图模型 @Published 变量?
- html - 如何在表格中显示嵌套 json 数组的数据
- node.js - 如何使用 nodejs、express、YouTube 数据 api 在我的网站上构建实时 Youtube 视频“喜欢”计数*无需刷新*
- graphql - 返回 graphql mongodb 中更新文档的 id
- python - 在主管下运行时如何显示 python 3 输出?