我想要做的是创建一个函数,该函数将获取一个列表作为输入和一个数字,并将删除该列表中等于该特定数字的节点。因此,如果我有一个链接列表,可以说:
struct num // list 1
{
char *val;
struct num *next;
};
我已经向该列表添加了 4 个项目,我希望能够删除第三个项目并返回包含现在 3 个项目的新列表。到目前为止我所尝试的一切都不起作用,我想是因为在删除其中一项后我没有正确链接剩余的项目。
既然你坚持说这就是我现在所拥有的
struct num1 *temp;
temp = head;
struct num1* deletend(int del){
for ( int i = 0; i < listSize; i++)
{
if (i == del){
free(temp);
}
temp = temp->next;
}
return temp;
}
最佳答案
以下代码解决了目的:
typedef struct num numNode; // typedef to escape repeated struct num
numNode* delete_item(numNode* startNode, int position)
{
int pos = 0;
numNode* current = NULL;
numNode* prev = NULL;
if ((start == NULL) || (position == 0)) // if empty list or 0th item deletion, return the list as it is
return start;
else if (position == 1) // if delete first item,
{
current = start; // this node to be deleted
start = start->next; // Set start to the next item
free current;
current = NULL; // delete the node
return start;
}
else
{
prev = start; // this will mark the previous node
current = prev->next; // this will mark the current node
pos = 2; // position 0, 1 taken care of
}
while ((current != NULL))
{
if (pos == position)
{
prev->next = current->next;
free current;
current = NULL;
break;
}
pos++;
}
return start;
}
关于c - 从链表中删除一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20272446/