我的循环链表代码适用于添加、搜索、计数、查看,但是一旦我从列表中删除一个条目,它就会与列表中的所有其他数据混淆。我知道错误在DeleteNode函数中,但无法弄清楚。请帮我解决这个问题 - 谢谢。
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
}*head,*temp,*curr,*prev,*p;
/* Prototypes */
void AddNode(int value);
int CountNode();
void SearchNode(int value);
void ViewAll();
void DeleteNode(int value);
/* Main */
int main(){
int choice,value;
printf("\n\n\n\t\t\tCircular Linked List\n\n\t\t\tSyed Danish Ali\n\n\t\t\tUBIT\n\n\n\t\t\t\tHit ENTER to continue...");
while(getche() != '\r'){
}
do{
system("cls");
printf("\n\nMENU\n=====\n\n[1] ADD\n[2] COUNT\n[3] SEARCH\n[4] VIEW ALL [5] DELETE\n[6] EXIT\n\nCHOICE:\t");
scanf("%d",&choice);
if(choice == 1){
printf("Enter data:\t"); scanf("%d",&value);
AddNode(value);
getch();
} else if(choice == 2){
printf("\n\n%d Node(s).",CountNode());
getch();
}else if(choice == 3){
printf("Enter the data to search:\t");
scanf("%d",&value);
SearchNode(value);
getch();
} else if(choice == 4){
ViewAll();
getch();
} else if(choice == 5){
printf("Enter the data to search:\t");
scanf("%d",&value);
DeleteNode(value);
getch();
} else if(choice == 6){
return 0;
}
}while(1);
}
void AddNode(int value){
temp = (struct Node *) malloc (sizeof(struct Node));
temp->data = value;
if(head == NULL){
head = temp;
temp->next = head;
} else {
curr = head;
while(curr->next != head){
curr = curr->next;
}
p = curr;
curr->next = temp;
temp->next = head;
}
printf("\n\nNode added.");
}
int CountNode(){
int k = 0;
if(head == NULL){
return 0;
} else {
curr = head;
while(curr->next != head){
k++;
curr = curr->next;
}
return k;
}
}
void SearchNode(int value){
int flag = 0,k = 0;
if (head == NULL){
printf("\n\nList is empty.");
} else {
curr = head;
while(curr->next != head){
if (curr->data == value){
flag = 1;
printf("\n\n%d found at index # %d.",value,k);
curr = curr->next;
} else {
curr = curr->next;
k++;
}
}
}
if(flag == 0)
printf("\n\nValue %d not found.",value);
}
void ViewAll(){
int counter = 0;
if(head == NULL)
printf("\n\nList is empty.");
else{
curr = head;
printf("LIST GENERATED:\n===============\n");
while(curr->next != head){
printf("\nElement # %d:\nData:\t%d",counter+1,curr->data);
curr = curr->next;
counter++;
}
}
}
void DeleteNode(int value){
int flag = 0;
if(head == NULL){
printf("\n\nList is empty.");
} else {
curr = head;
while(curr->next != head){
if(curr->data == value){
printf("\n\nValue found.");
flag = 1;
if(curr == head){
curr->next = head;
free(curr);
} else {
prev->next = curr->next;
free(curr);
}
} else {
prev = curr;
curr = curr->next;
}
}
printf("Node deleted.");
}
if(flag == 0)
printf("\n\nValue not found.");
}