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;
}
谢谢!
答案 0 :(得分: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;
答案 1 :(得分:0)