所以我正在编写这个程序,当节点被删除时,如果它大于它左边的节点,并找到没有节点被删除的迭代次数。我想到了这个,但是 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 plants\n");
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("%d\t",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
}
}
关于c - 与左节点比较后删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35394316/