这个改用"-2"作为删除标记,则可以正确找到707所在的结点。感觉还是找不到707所在的结点吧
以下答案引用自GPT-3大模型,请合理使用:
不可以,改用“-2”作为删除标记的情况下,并不能正确找到707节点所在的位置。原因是,当使用-2作为删除标记时,遍历循环也会遍历到“-2”这个节点,这时候得到的结果就和之前不一样了。如果要正确找到707所在的结点,应该使用删除指针来完成,代码如下:
struct node
{
int data;
struct node *next;
struct node *prev;
}
int find_element(struct node *head, int element)
{
struct node *curr = head;
while (curr != NULL)
{
if (curr->data == element)
return 1;
curr = curr->next;
}
return 0;
}
void deleteNode(struct node** head, int position)
{
//首先声明一个struct node类型指针,指向head结点
struct node* current/*移动指针*/, *prev/*记录前驱结点*/;
int i;
current = *head;
if (position == 0)//如果删除头结点
{
*head = (*head)->next;
}
else
{
for (i = 0; current != NULL && i < position ; i++)
{
prev = current;
current = current->next;
}
//如果position大于链表长度
if (current == NULL)
return;
prev->next = current->next;
}
free(current);
}
int main()
{
struct node *head = NULL;
struct node *second = NULL;
struct node *third = NULL;
// 动态内存分配
head = (struct node *)malloc(sizeof(struct node));
second = (struct node *)malloc(sizeof(struct node));
third = (struct node *)malloc(sizeof(struct node));
head->data = 777;
head->next = second;
head->prev = NULL;
second->data = 607;
second->next = third;
second->prev = head;
third->data = 707;
third->next = NULL;
third->prev = second;
if(find_element(head, 707))
{
printf("Element found.");
}
else
{
printf("Element not found.");
}
deleteNode(&head, 2);
return 0;
}
如果我的回答解决了您的问题,请采纳我的回答