微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

反转C中的双向链表

如何解决反转C中的双向链表

我写了反向逻辑,但它没有给出所需的输出。实际上,当我只打印链表遍历函数时,它会很好地打印所有元素,但是当我调用反向函数调用遍历函数后,它没有给出反向链表。 我不明白我错在哪里。请解决我的问题。 提前致谢!!

#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);
}
Output:
Element:10
Element:20
Element:30
Element:40
Element:10
Element:40

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。