所以我在删除节点时编写这个程序,如果它大于它左侧的节点,并找到迭代次数,之后没有节点被删除。我想出了这个,但int days
始终保持在 0。
#include<stdio.h>
#include<malloc.h>
struct plants{
int val;
struct plants *next;
};
void printlist();
int main(){
int counter=0;
int size=0;
int days=0;
printf("Enter the number of plantsn");
scanf("%d",&size);
printf("Enter the amount of pesticide each plant has.n");
struct plants* head = NULL;
while( counter < size )
{
struct plants * current = malloc(sizeof(struct plants));
scanf( "%d", ¤t->val);
current->next = head;
head = current;
counter ++;
}
struct plants *temp = head;
printf("You have entered.n");
while(temp!=NULL){
printf("%dt",temp->val);
temp=temp->next;
}
struct plants *now = head;
while(counter<size){
if(now->val < now->next->val){
struct plants* nextNext = now->next->next;
days++;
free(now->next);
now->next= nextNext;
counter++;
}
else{
now = now->next;
}
}
printf("The days after which the plants stop dying %d.n",days);
}
你需要一个指向要删除的节点的指针的指针,这样你就可以把节点的后继节点放到它的位置:
int days = 0;
struct plants **now = &head;
while( *now != NULL && (*now)->next != NULL ) // do as long as there are two nodes to compare
{
struct plants *next = (*now)->next; // successor of the node
if ( (*now)->val < next->val ) // test if successor node is greater than node
{
free( *now ); // free the node
*now = next; // put successor of the node in place of the node
}
else
{
now = &((*now)->next); // step one forward
days ++; // increment counter because no node was deleted
}
}
另一种解决方案是记住当前节点的前置节点:
int days = 0;
struct plants *now = head; // start at head of list
struct plants *prev = NULL; // predecessor of head is NULL
while( now != NULL && now->next != NULL ) // do as long as there are two nodes to compare
{
struct plants *next = now->next; // successor of the node
if ( now->val < next->val ) // test if successor node is greater than node
{
free( now ); // free the node
if ( prev == NULL ) // put successor of the node in place of the node
head = next; // the first node of the list was deleted
else
prev->next = next; // successor of predecessor is predecessor of deleted node
now = next; // step one forward
// note "prev" does not change in this case
}
else
{
prev = now;
now = now->next; // step one forward
days ++; // increment counter because no node was deleted
}
}
看:
while( counter < size )
{
struct plants * current = malloc(sizeof(struct plants));
scanf( "%d", ¤t->val);
current->next = head;
head = current;
counter ++;
}
//counter == size
struct plants *temp = head;
printf("You have entered.n");
while(temp!=NULL){
printf("%dt",temp->val);
temp=temp->next;
}
struct plants *now = head;
//counter == size
while(counter<size){
if(now->val < now->next->val){
struct plants* nextNext = now->next->next;
days++;
free(now->next);
now->next= nextNext;
counter++;
}
else{
now = now->next;
}
}
您没有重置counter
的值