首页 > 解决方案 > 反转链表

问题描述

#include<iostream>
using namespace std;

struct node{
    int data;
    node* next;
};

node *head=NULL;

void print(struct node*)
{
    node *temp=head;
    while(temp!=NULL)
    {
        cout<<temp->data;
        temp=temp->next;
    }
}

struct node* insert(struct node* head,int x)
{
    node *temp=new node();
    temp->data=x;
    temp->next=head;
    head=temp;
    return head;
}

struct node* reverse(struct node* head)
{
    node *current,*next,*prev;
    current=head;
    prev=NULL;
    next=NULL;
    while(current!=NULL)
    {
        next=current->next;
        current->next=prev;
        current=next;
        prev=current;
    }
    head=prev;
    return head;
}

int main()
{
    struct node *head=NULL;
    head=insert(head,2);
    head=insert(head,4);
    head=insert(head,3);
    head=insert(head,8);
    print(head);
    head=reverse(head);
    print(head);
    return 0;

}

有人能指出这段代码有什么问题吗?我试过执行它,但我似乎遇到了打印问题。即使在我尝试更正之后,它也只打印链表而不是反向链表。我是初学者。谢谢。

标签: c++linked-list

解决方案


问题:

您的代码有很多需要解决的问题,但特别指出您的问题,问题出在 print 函数中。

你的问题有2个问题:

  1. 您正在使用一个名为head始终为 NULL 的全局变量,而不是使用作为参数传递的全局变量。
  2. 反向功能不正确。

解决方案

改变这个

node *head=NULL;

void print(struct node*)
{
    node *temp=head;
    while(temp!=NULL)
    {
        cout<<temp->data;
        temp=temp->next;
    }
}

为了这:

void print(struct node* head)
{
    node *temp=head;
    while(temp!=NULL)
    {
        cout<<temp->data;
        temp=temp->next;
    }
}

这样,您将使用参数中的节点,而不是全局范围内始终为 NULL 的节点。

在反向功能更改中:

current = next;
prev = current;

为了这:

prev = current;
current = next;

附加信息:

  1. using namespace std;是一种不好的做法(更多信息在这里)。
  2. 您可能应该添加一个类来用方法包装链表。
  3. 我会使用nullptr而不是NULL避免混淆(更多信息在这里)。
  4. 也许你应该搜索一本好的 C++ 教科书

完整代码:

#include<iostream>

struct node{
public:
    int data;
    node* next;
};

class linkedList
{
private:
    node* head;
public:
    linkedList();
    void print();
    void reverse();
    void insert(int);
    void invert();
};

linkedList::linkedList()
{
    head = nullptr;
}

void linkedList::print()
{
    node *temp = this->head;
    while(temp!=nullptr)
    {
        std::cout << temp->data;
        temp = temp->next;
    }
}

void linkedList::insert(int x)
{
    node *temp = new node();
    temp->data = x;
    temp->next = this->head;
    this->head = temp;
}

void linkedList::reverse()
{
    node *current,*next,*prev;
    current = this->head;
    prev = nullptr;
    next = nullptr;
    while(current != nullptr)
    {
        next = current->next;
        current->next=prev;
        prev = current;
        current = next;
    }
    this->head = prev;
}

int main()
{
    linkedList myList;
    myList.insert(4);
    myList.insert(4);
    myList.insert(3);
    myList.insert(8);
    myList.print();
    myList.reverse();
    myList.print();
    return 0;
}

推荐阅读