gpt4 book ai didi

c++ - 循环链表 : How to correct my remove node function?

转载 作者:行者123 更新时间:2023-11-27 23:56:29 24 4
gpt4 key购买 nike

我正在学习循环链表。我在调用 deleteNodeByKey() 删除头节点时遇到问题。它适用于要删除的其余节点。如果删除节点是头,为什么它不起作用?

#include <iostream>
#include <stdlib.h>
using namespace std;

/* structure for a node */
struct node
{
int data;
struct node *next;
};

/* Function to insert a node at the begining of a Circular
linked list */
void push(struct node **head_ref, int data)
{
struct node *ptr = (struct node*)malloc(sizeof(struct node));
ptr->data = data;
ptr->next = *head_ref;
struct node *temp = *head_ref;
/* If linked list is not NULL then set the next of last node.
It is going to last node by circling 1 times.
*/
if(*head_ref != NULL){
while(temp->next != *head_ref){
temp = temp->next;
}
//set last node by ptr
temp->next = ptr;
}
else{
// 1 node circular linked list
ptr->next = ptr;
}
// after push ptr is the new node
*head_ref = ptr;
}

//get the previous node
struct node* getPreviousNode(struct node* current_node){
struct node* prev = current_node;
while(prev->next != NULL && prev->next->data != current_node->data ){
prev = prev->next;
}
return prev;
}


/* Given a reference (pointer to pointer) to the head of a list
and a key, deletes the first occurrence of key in linked list */
void deleteNodeByKey(struct node **head_ref, int key)
{
// Store head node
struct node* current_node = *head_ref, *prev;


while(current_node != NULL && current_node->data != key){
current_node = current_node->next;
}

if(current_node == NULL){
return;
}

//Removing the node
if(current_node->data == key){
prev = getPreviousNode(current_node);
prev->next = current_node->next;
current_node->next = NULL;
free(current_node);
return;
}
}


/* Function to print nodes in a given Circular linked list */
void printList(struct node *head)
{
struct node *temp = head;
if(head != NULL){
/*
do-while because at 1st temp points head
and after 1 rotation temp wil come back to head again
*/
do{
cout<<temp->data<<' ';
temp = temp->next;
}
while(temp != head);
cout<<endl;
}
}

int main() {
/* Initialize lists as empty */
struct node *head = NULL;
/* Created linked list will be 11->2->56->12 */
push(&head, 12);
push(&head, 56);
push(&head, 2);
push(&head, 11);
cout<<"Contents of Circular Linked List"<<endl;
printList(head);

deleteNodeByKey(&head, 11);
printList(head);

return 0;
}

这是代码链接:Source Code

最佳答案

头节点不应该是链表的一部分,它应该是一个单独的节点,保存链表第一个节点的地址。因此,当您删除第一个节点时,使 Head 指向第一个节点的下一个节点,并且当您遵循此结构时,头节点将与其他节点相同。 enter image description here

像这样声明 head:

struct node* head;
head = *first;

要先删除

head = head->next;
free(first);`

关于c++ - 循环链表 : How to correct my remove node function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42269983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com