我正在研究双链表。元素以正常顺序完美打印。但我无法以相反的顺序显示它们。我在网上找到的一种方法是交换方法。但我想在不交换方法的情况下打印它们。有没有其他可能的方法可以实现这一目标?
提前致谢。
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
struct node *prev;
}list;
list *start=NULL;
list *end=NULL;
list *create(list *);
list *display(list *);
list *reverse_display(list *);
int main()
{
int n;
printf("1: Create List\n");
printf("2: Display\n");
printf("3: Reverse Display\n");
for(;;)
{
printf("Enter choice: ");
scanf("%d",&n);
switch(n)
{
case 1: start = create(start);
break;
case 2: start = display(start);
break;
case 3: start = reverse_display(start);
break;
default: printf("Wrong Input!!!\n");
exit(0);
}
}
}
list *create(list *start)
{
int num;
list *new_node , *ptr;
printf("Enter the number: ");
scanf("%d",&num);
new_node = (list *)malloc(sizeof(list));
new_node->data = num;
if(start == NULL)
{
new_node->prev = NULL;
new_node->next = NULL;
start = new_node;
}
else
{
ptr = start;
while(ptr->next != NULL)
ptr = ptr->next;
ptr->next = new_node;
new_node->prev = ptr;
new_node->next = NULL;
}
return start;
}
list *display(list *start)
{
list *ptr;
ptr = start;
printf("\nElements in original order:\n");
if(start == NULL)
printf("Empty List!!!\n");
else
{
while(ptr!=NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
return start;
}
list *reverse_display(list *start)
{
list *ptr;
ptr = end;
printf("\nElements in reverse order\n");
while(ptr != start->prev)
{
printf("%d\n",ptr->data);
ptr = ptr->prev;
}
return start;
}