[英]trouble in with reverse viewing/search function in double linked list C programming
大家好,这是我第一次做双链表,所以我不太确定我在这里做什么,需要一些帮助来检查代码,谢谢,这是我在做评论时所做的。 我在这里执行的功能是打印,打印反向,在链表中计数元素以及搜索功能以确定该节点是否存在
void printListfow() //print the list in forward manner
{
CLR;
struct node *tmpval; //declare a temp storage
if(start==NULL) //if 1st node = null,then nth is inside,nth to print
{
printf("List is empty\n");
return;
}
tmpval=start; //assign the head/start to temp storage to retrieve data in 1st node
printf("List of customer details: \n");
while(tmpval!=NULL) //keep doing till it is NULL/the end
{
printf("%d ", tmpval->detail); //print the 'detail' which is in the node temp is pointing at
tmpval=tmpval->next; //assign next node to the temp storage so that it can be printed again
}
}
void printListrev() //print in reverse manner
{
CLR;
struct node *tmpval; //temp storage
if(start==NULL) //
{
printf("List is empty\n");
return;
}
tmpval=start; //assign start to tmpval to retrieve value
printf("List of customer details: \n");
tmpval=tmpval->prev //move backward and assign the data to tmpval
printf("%d",tmpval->detail) //print it
}
void count() //count total number of records
{ struct node *x;
x=start; //assign value of start to temp storage
int ctr=0; //initialize counter
while(x!=NULL)
{
x=x->next; //keep going to next node and then increase the counter
ctr++;
}
printf("Number of customer records are %d\n",ctr);
}
int getNode(node *tmp ,int cust) //when user wants to delete a customer ID and its details, this will search through the list,then if found,pass the value to another function for deletion
{
tmp=tmp->cust;
while(tmp!=NULL)
{
if(tmp->detail == cust) //check if detail[ID stored] is same as requested[cust]
{
return 1;
}tmp=tmp->next; //if not same,then move to next one
}return 0;
}
谢谢!
在printListrev()
上下文中:
除非这是一个循环的双向链表,否则在最后一个元素之后是第一个元素的情况下, start
将具有上一个元素NULL。 因此,没有必要像在这里那样访问start
的上一个字段:
tmpval=start;
...
tmpval=tmpval->prev;
为此,您可以将另一个指针保留在列表末尾。
其他替代方案包括:
递归函数:
void printrev(struct node *s)
{
if (s == NULL)
return;
printrev(s->next);
printf("%d ", s->detail);
}
迭代功能:
void printrev()
{
struct node *end;
for (end = start; end->next != NULL; end = end->next)
;
for (; end != NULL; end = end->prev)
printf("%d ", end->detail);
}
您的getNode
用途有限。 假设,如果要删除元素,则getnode
将仅返回是否存在元素。 假设存在,则deleteNode
函数在删除之前仍必须迭代到列表中的适当元素。
这可以通过getNode
返回指向节点的指针来解决:
node *getNode(int x)
{
node *t;
for (t = start; t != NULL; t = t->next)
if (t->detail == x)
return t;
return t;
}
现在,您可以编写删除代码,如下所示:
void delNode(node *n)
{
n->prev->next = n->next;
n->next->prev = n->prev;
free(n);
}
并调用如下:
node *n;
if ((n = getNode(x)) != NULL)
delNode(n);
我假设您的struct
是:
struct node {
int detail;
struct node *next;
struct node *right;
};
typedef struct node * node;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.