我用C语言做了一个单链路的列表,我试图根据提供的整数值从列表中删除一个特定元素的函数,这个整数值对应于一个特定的节点。
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);
}
经过一些调试,我发现。该函数工作正常,因为它成功地检测并删除了节点。
但打印整个列表会得到奇怪的结果。
完整的代码。
#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();
}
这是我在删除了值为40的节点后试图打印列表时得到的输出截图。
这些重复的值让它陷入了一个无限循环!
首先,使用一个全局变量作为指向列表的 heda 节点的指针,以及当函数依赖于全局变量时,这是一个坏主意。在这种情况下,你无法创建一个以上的列表。
尽管如此,函数 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;
}
根据你的删除功能,如果你要删除的节点不在列表中,但即使在你的删除功能之后,也会给出一个消息,即
found the val to be
这是完全错误的......所以你可以这样写你的删除函数
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");
}