如果列表有多个节点,我的功能可以删除列表前面的节点。 如果列表中只剩下一个节点,则不会发生删除..
#include<stdio.h>
#include<stdlib.h>
//Circular linked list node structure
typedef struct circularLinkedListNode{
int data;
struct circularLinkedListNode *next;
}circularLinkedListNode;
circularLinkedListNode *head = NULL;
//Traversal of circular linked list
void traversal()
{
circularLinkedListNode *current = head;
if(current == NULL)
{
printf("\nThe list is empty!!");
}
else
{
do {
printf("%d--", current->data);
current = current->next;
} while (current != head);
}
}
//Insertion at the beginning of the list
void insertAtBeginning(int data)
{
circularLinkedListNode *newNode = (circularLinkedListNode *)malloc(sizeof(circularLinkedListNode));
//Create a new node and point it to itself
newNode->data = data;
newNode->next = newNode;
if(head == NULL)
{
head = newNode;
}
else
{
circularLinkedListNode *current = head;
while (current->next != head) {
current = current->next;
}
current->next = newNode;
newNode->next = head;
head = newNode;
}
}
//Insertion at the end of the list
void insertAtEnd(int data)
{
circularLinkedListNode *newNode = (circularLinkedListNode *)malloc(sizeof(circularLinkedListNode));
newNode->data = data;
newNode->next = newNode;
if(head == NULL)
{
head = newNode;
}
else
{
circularLinkedListNode *current = head;
while(current->next != head)
{
current = current->next;
}
newNode->next = head;
current->next = newNode;
}
}
主要问题是这个功能:::::
//Deletion of node at the beginning
void deleteATBeginning()
{
if(head == NULL)
{
printf("\nEmpty list!!");
}
else
{
circularLinkedListNode *nodeToDelete = head;
circularLinkedListNode *current = head;
while(current->next != head)
{
current = current->next;
}
current->next = head->next;
head = head->next;
free(nodeToDelete);
}
}
int main()
{
int data, choice;
while (1)
{
printf("\n***CIRCULAR LINKED LIST***\n1.Traversal\n2.Insertion at the beginning\n3.Insertion at the end\n4.Deletion of front node\n5.Deletion of end node\n6.Exit\nEnter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
traversal();
break;
case 2:
printf("Enter the data: ");
scanf("%d", &data);
insertAtBeginning(data);
break;
case 3:
printf("Enter the data: ");
scanf("%d", &data);
insertAtEnd(data);
break;
case 4:
deleteATBeginning();
break;
case 6:
return 0;
break;
default:
printf("Wrong choice!! Please try again...");
break;
}
}
}
答案 0 :(得分:1)
您的代码看起来有点复杂,但它应该有效。我想当你说“列表删除没有发生”时,你并没有正确地寻找它。
您正在寻找成为null
以确认删除发生的人:
if(head == NULL)
{
printf("\nEmpty list!!");
但是你从来没有考虑过删除列表中唯一节点的特殊情况,因此head永远不会成为null
(这不会自己发生)。
这可以很简单:
if(head->next == head) // if the head's next node is itself
{
head->next = null;
free(nodeToDelete);
head = null;
}
else
{
while(current->next != head)
{
current = current->next;
// ...rest of your code as is
您的代码当前free
正在head
指向的内存,但它没有释放(null
')内存位置,因此您的head
指针仍指向内存,但此内存不再由您的程序拥有。这是一个悬垂的指针。您可能仍然将节点的内容视为“有效”,但这只是偶然的,因为此时没有其他内容进入并重新分配内存。