c++ - 反转链表
问题描述
#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;
}
有人能指出这段代码有什么问题吗?我试过执行它,但我似乎遇到了打印问题。即使在我尝试更正之后,它也只打印链表而不是反向链表。我是初学者。谢谢。
解决方案
问题:
您的代码有很多需要解决的问题,但特别指出您的问题,问题出在 print 函数中。
你的问题有2个问题:
- 您正在使用一个名为
head
始终为 NULL 的全局变量,而不是使用作为参数传递的全局变量。 - 反向功能不正确。
解决方案
改变这个
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;
附加信息:
using namespace std;
是一种不好的做法(更多信息在这里)。- 您可能应该添加一个类来用方法包装链表。
- 我会使用
nullptr
而不是NULL
避免混淆(更多信息在这里)。 - 也许你应该搜索一本好的 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;
}
推荐阅读
- typescript - 打字稿 - 逐步扩展对象的类型
- ios - iOS 以 Data Swift 形式上传图片
- google-apps-script - 如何通过 Google App Script 打开打印窗口(导出为 pdf)?
- powershell - 如何使用powershell打开选定的对象
- java - 可点击的 jface AutoCompleteField
- r - 计算 R 中周期性(循环)变量的均值和方差
- java - Ant 没有遵循 javac 的“可执行”属性
- javascript - 单击(宽度)时更改属性的功能不起作用
- video-streaming - ICE 服务器(google stuns)在 NAT 之后工作了 8 次,但从那时起就无法工作但在本地工作。为什么?
- python - Lark Parser: No terminal defined for ':' (Seeming bias against colon character ":")