0
當我刪除第一個節點時,我的代碼給出了無限循環錯誤,其他的刪除沒問題。當我刪除第一個節點時,它會生成一個無限循環錯誤
#include <stdio.h>
#include <stdlib.h>
struct node //Node
{
int info;
struct node * link;
};
//insertion at begin
struct node * AddAtBegin(struct node * start, int data) {
struct node * p;
p = (struct node *) malloc(sizeof(struct node));
p - > info = data;
p - > link = start;
start = p;
return start;
}
//insertion at End
struct node * AddAtEnd(struct node * start, int data) {
struct node * p, * q = start;
p = (struct node *) malloc(sizeof(struct node));
p - > info = data;
p - > link = NULL;
while (q - > link != NULL)
q = q - > link;
q - > link = p;
return start;
}
//insertion after any given node
struct node * AddAfter(struct node * start, int data, int node) {
if (node == ' ')
return start;
struct node * temp, * p = start;
temp = (struct node *) malloc(sizeof(struct node));
temp - > info = data;
while (p != NULL) {
if (p - > info == node) {
temp - > link = p - > link;
p - > link = temp;
return start;
}
p = p - > link;
}
printf("Not Found Your Node");
return start;
}
//insertion before any given node
struct node * AddBefore(struct node * start, int data, int node) {
if (start == NULL) {
printf("List is Empty");
return start;
}
struct node * p, * q = start;
p = (struct node *) malloc(sizeof(struct node));
p - > info = data;
if (start - > info == node) {
p - > link = start;
start = p;
return start;
}
while (q - > link != NULL) {
if (q - > link - > info == node) {
p - > link = q - > link;
q - > link = p;
return start;
}
q = q - > link;
}
printf("NOT found node");
return start;
}
// deletion of node
int Delete(struct node * start, int data) {
struct node * p = start;
struct node * temp = NULL;
if (start == NULL) {
printf("Epty list");
exit(1);
}
if (p - > info == data) {
temp = start;
start = p - > link;
free(temp);
printf("After Deletion of %d == ", data);
return 0;
}
while (p - > link != NULL) {
if (p - > link - > info == data) {
temp = p - > link;
p - > link = temp - > link;
free(temp);
printf("After Deletion of %d == ", data);
return 0;
}
p = p - > link;
}
printf("Not Found In The List");
return 0;
}
//display of all nodes
void Display(struct node * start) {
struct node * p = start;
while (p != NULL) {
printf("%d \t", p - > info);
p = p - > link;
}
return;
}
int main() {
struct node * start = NULL;
int i;
start = AddAtBegin(start, 2);
start = AddAtBegin(start, 1);
start = AddAtEnd(start, 4);
start = AddAtEnd(start, 5);
start = AddAfter(start, 6, 5);
start = AddAfter(start, 3, 2);
start = AddBefore(start, 7, 6);
start = AddBefore(start, 79, 1);
printf("List is \n");
Display(start);
printf("\n");
scanf("%d", & i);
Delete(start, i);
Display(start);
Delete(start, 7);
Display(start);
Delete(start, 79);
Display(start);
return 0;
}