[英]Deleting a specific node from singly linked list in C
我在 C 中創建了一個單鏈表,我正在嘗試編寫一個 function,它根據 Z157DB7DF530023575515D366C9B672E8 值從列表中刪除特定元素,該值對應於一個特定的節點。
void deleteNodeVar(int val)
{
struct node *t, *temp, *temp2;
t = START;
while(t -> info != val)
{
if(t -> ptr == NULL) { break; }
t = t -> ptr;
}
printf("\nfound the val to be %d\n",t -> info);
temp = t -> ptr;
t -> ptr = temp -> ptr;
printf("now will free the node with value %d \n",t -> info);
free(t);
}
經過一番調試,我發現: function 工作正常,因為它檢測到並成功刪除了節點
但是打印整個列表會產生奇怪的結果。
完整代碼:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
};
struct node *START = NULL;
struct node* createNode()
{
struct node *p;
p = (struct node*) malloc(sizeof(struct node));
return p;
}
//inserting node
void insertNode(int val)
{
struct node *temp, *t;
temp = createNode();
temp -> info = val;
temp -> ptr = NULL;
if(START == NULL){ START = temp; }
else
{
t = START;
while(t -> ptr != NULL)
{
t = t -> ptr;
}
t -> ptr = temp;
}
}
void pop()
{
struct node *t;
t = START;
if(START == NULL) { printf("THE LIST IS EMPTY\n"); }
else
{
START = START -> ptr;
free(t);
}
}
//here are the 2 functions below in which I have problem
void deleteNodeVar(int val)
{
struct node *t, *temp, *temp2;
t = START;
while(t -> info != val)
{
if(t -> ptr == NULL) { break; }
t = t -> ptr;
}
printf("\nfound the val to be %d\n",t -> info);
temp = t -> ptr;
t -> ptr = temp -> ptr;
printf("now will free the val with value %d \n",t -> info);
free(t);
}
void viewList()
{
struct node *t, *temp;
t = START;
while(t != NULL)
{
printf("%d -> ",t->info);
t = t -> ptr;
}
}
int main()
{
insertNode(10);
insertNode(20);
insertNode(40);
insertNode(100);
viewList();
int v;
printf("\nEnter to delete: ");
scanf("%d",&v);
deleteNodeVar(v);
viewList();
}
這是 output 的屏幕截圖,我在刪除值為 40 的節點后嘗試打印列表后得到:
它正在與這些重復值陷入無限循環!
對於初學者來說,當函數依賴於全局變量時,使用全局變量作為指向列表 heda 節點的指針是一個壞主意。 在這種情況下,您無法創建多個列表。
盡管如此,function deleteNodeVar
可以通過以下方式定義
int deleteNodeVar(int val)
{
node *prev = NULL, *current = START;
while ( current != NULL && current->info != val )
{
prev = current;
current = current->ptr;
}
int success = current != NULL;
if ( success )
{
if ( prev == NULL )
{
START = START->ptr;
}
else
{
prev->ptr = current->ptr;
}
free( current );
}
return success;
}
根據您的刪除 function 如果您要刪除的列表中不存在該節點但即使在您刪除 function 之后也會給出一條消息
found the val to be
這是完全錯誤的......所以你可以這樣寫你的刪除 function
void deleteNodeVar(int val)
{
node *p ='\0', *n = START;
int flag=0;
while ( n != '\0' && n->info != val )
{
p =n;
n =n->ptr;
}
if(n!='\0')
flag=1;
if ( flag )
{
if ( p == '\0' )
{
START = START->ptr;
}
else
{
p->ptr = n->ptr;
}
printf("\nfound the val to be %d\n",n-> info);
free( n );
}
else
printf("The node is not present list\n");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.