在C语言中反转双链表
我写了反向逻辑,但它并没有给出期望的输出。实际上,当我只打印链表遍历函数时,它会精细地打印所有元素,但当我调用反向函数时,调用遍历函数后,它并没有给出反向链表。 我没有错。请解决我的问题。 提前谢谢在C语言中反转双链表,c,data-structures,C,Data Structures,我写了反向逻辑,但它并没有给出期望的输出。实际上,当我只打印链表遍历函数时,它会精细地打印所有元素,但当我调用反向函数时,调用遍历函数后,它并没有给出反向链表。 我没有错。请解决我的问题。 提前谢谢 #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; struct Node *prev; }; void linkedListTra
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
struct Node *prev;
};
void linkedListTransversal(struct Node *ptr)
{
while (ptr != NULL)//&& ptr->prev != NULL
{
printf("Element:%d\n", ptr->data);
ptr = ptr->next;
}
}
void linkedListRevTransversal(struct Node *head)
{
struct Node * temp=NULL;
struct Node * p=head;
while (p != NULL)
{
temp=p->prev;
p->prev=p->next;
p->next=temp;
p=p->prev;
}
if(temp != NULL )
head = temp->prev;
}
int main()
{
struct Node *head;
struct Node *second;
struct Node *third;
struct Node *fourth;
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
fourth = (struct Node *)malloc(sizeof(struct Node));
head->data = 10;
head->prev=NULL;
head->next = second;
second->data = 20;
head->prev=head;
second->next = third;
third->data = 30;
head->prev=third;
third->next = fourth;
fourth->data = 40;
head->prev=fourth;
fourth->next = NULL;
linkedListTransversal(head);
linkedListRevTransversal(head);
linkedListTransversal(head);
}
“我没有弄错。”
——您是否尝试过在调试器中逐行运行代码,同时监视所有变量的值,以确定程序在哪一点停止运行?如果未尝试此操作,则可能需要阅读以下内容:您可能还需要阅读以下内容:。为了向后遍历双链接列表,必须从尾部开始,而不是从头部开始。我假设函数linkedListTransversal
应该向前遍历列表,打印它遇到的每个节点。但是函数linkedListRevTransversal
应该做什么呢?从尾部到头部反向遍历列表,同时打印遇到的每个节点?或者它只是简单地反转列表,而不打印任何内容?如果您希望实际反转链接列表(而不是只按相反顺序打印),则需要一个指针指向链接列表的头部,另一个指针指向尾部。这样,就可以交换两个节点。然后,你移动两个指针,一个节点靠近中间并重复,直到两个指针在中间相遇。请用你的最新代码更新你的问题。通常,如果这样的更改会使其中一个答案无效,则不应更新您的问题。但既然你的问题还没有答案,这不是问题,所以应该没问题。