[英]Getting error in deleting a node in a linked list using “while loop” but not with “for loop”
我編寫了一個創建,刪除和插入鏈表的程序,如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int value;
struct node *link;
};
struct node *head;
int menu();
int create_insert();
int delete();
int print();
int main()
{
head = malloc(sizeof(struct node));
menu();
return 0;
}
int menu()
{
int n;
while(1)
{
printf("\nMENU\n");
printf(" 1.Create & Insert\n 2.Search\n 3.Display\n 4.Delete \n 5.Exit\n");
printf("?: ");
scanf("%d",&n);
switch(n)
{
case 1:create_insert();print();break;
case 4:delete();print();break;
default : printf("Enter correct choice.");
}
}
return 0;
}
int delete()
{
struct node *temp,*temp1;
temp1 = NULL ;
int val;
temp = head ;
printf("\nEnter the value to be deleted: ");
scanf("%d", &val);
while ( temp->link != NULL || temp -> value == val )
{
//printf("%d->", temp->value) ;
temp1 = temp;
temp = temp->link ;
//printf("I am in while \n");
}
//printf("I am outside while \n");
if ( temp == NULL )
{
printf("%d is not found.\n",val);
}
else
{
if ( temp1 == NULL )
{
head = head -> link ;
}
else
{
temp1->link = temp -> link ;
}
}
//printf("NULL\n");
return 0;
}
int create_insert()
{
int val,check;
printf("Enter the first value to be inserted: ");
scanf("%d",&head->value);
head->link = NULL ;
printf("Want to insert more? ( 0 to break ): ");
scanf("%d",&check);
while( check != 0 )
{
printf("Enter the value to be inserted: ");
scanf("%d", &val);
struct node *new_node = malloc(sizeof(struct node));
new_node -> value = val ;
new_node -> link = head ;
head = new_node ;
printf("Want to insert more? ( 0 to break ): ");
scanf("%d",&check);
}
return 0;
}
int print()
{
struct node *temp;
temp = head ;
printf("\nLinked list is: ");
while ( temp != NULL )
{
printf("%d->", temp->value) ;
temp = temp->link ;
}
printf("NULL\n");
return 0;
}
抱歉,代碼有點冗長。 在這里,我在刪除函數中有一個while循環,如下所示:
while ( temp->link != NULL || temp -> value == val )
{
//printf("%d->", temp->value) ;
temp1 = temp;
temp = temp->link ;
//printf("I am in while \n");
}
//printf("I am outside while \n");
if ( temp == NULL )
{
printf("%d is not found.\n",val);
}
else
{
if ( temp1 == NULL )
{
head = head -> link ;
}
else
{
temp1->link = temp -> link ;
}
}
此循環在這里不起作用,僅刪除最后一個元素。 現在,我將其替換為for循環,如下所示:
for ( temp = head , temp1 = NULL ; temp != NULL && temp->value != val ; temp1 = temp , temp = temp->link)
{}
if ( temp1 == NULL )
{
head = head -> link ;
}
else
{
temp1 -> link = temp -> link ;
free(temp);
}
運行良好。 請在while循環中告訴我哪里錯了。
循環不一樣!!!
while
循環中的條件:
temp->link != NULL || temp->value == val
for
循環中的條件:
temp->link != NULL && temp->value != val
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.