我寫了下面的代碼,但執行create()函數後停止工作。我想從頭節點開始刪除備用元素。我的delete_Alt()函數是否正確?請告訴我我錯在哪裏。如何刪除C中的雙向鏈表中的備用節點?
#include <stdio.h>
#include <stdlib.h>
// using a structure
typedef struct mynode {
int data;
struct mynode *prev; // to point to previous node
struct mynode *link; // to point to next node
} node;
node *head = NULL;
// creating the list
void create() {
node *p, *q;
int ch;
do {
p = (node *)malloc(sizeof(node));
printf("enter data\n");
scanf("%d", &p->data);
if (head == NULL)
{
p->prev = head;
q = p;
}
else
{
p->prev = q;
p->link = NULL;
q->link = p;
q = p;
}
printf("create another node?, press 1 ");
scanf ("%d",&ch);
} while(ch==1);
}
//to delete alternate elements
void delete_Alt() {
if (head == NULL)
printf("Empty list...ERROR");
node *previous, *current, *next;
previous = head;
current = head->link;
while (previous !=NULL && current != NULL) {
previous->prev = current->prev;
previous->link = current->link;
next = current->link;
previous->link = next;
next->prev = previous;
free(current);
}
}
// print the list
void display() {
node *temp;
temp = head;
while (temp != NULL) {
printf("%d ",temp->data);
temp = temp->link;
}
printf("\n");
}
int main() {
node *head = NULL;
create();
printf("List before deleting is: ");
display();
delete_Alt();
printf("List after deleting is: ");
display();
return 0;
}
在'while'循環的生命週期中考慮'current'的值(它包含的地址)。你可以在循環之前設置一次*。它永遠不會再被改變,但它也被反覆地解除和「免費」。這不可能*是正確的。它也高度懷疑,如果頭部指向的最初節點是第一個被釋放的,爲什麼head中保存的地址永遠不會改變?一個*預期*輸入/輸出樣本會做這個問題,順便說一句。 – WhozCraig