c++ - 使用单链表反转字符串
问题描述
我正在尝试使用链表打印字符串的反向。假设我的字符串是“World is full of good people”,它应该打印“people good of full is World”
#include <iostream>
using namespace std;
/******** Fucntions Prototype *********/
void printList();
typedef struct Node
{
string data;
struct Node *next;
}node;
struct Node* newNode(string userData)
{
node *temp = new Node;
temp->data = userData;
temp->next = NULL;
return temp;
}
void printList(node* head)
{
node *temp = head;
while(temp != NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
}
void reverseList(node *head)
{
node *curr = head;
node *prev = NULL, *next = NULL;
while(curr != NULL)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
}
int main()
{
node *head = newNode("World");
head->next = newNode("is");
head->next->next = newNode("full");
head->next->next->next = newNode("of");
head->next->next->next->next = newNode("good");
head->next->next->next->next->next = newNode("people");
cout<<"Linked list before reverse is:\n";
printList(head);
cout<<"\n";
reverseList(head);
cout<<"Linked list after reverse is:\n";
printList(head);
return 0;
}
因此,如果字符串是“World is full of good people”,则预期输出是“people good of full is world”,因此节点反转。但是将“世界”作为输出
解决方案
所以颠倒列表不是问题,看到你传递了head
值所以你实际上是在对head
. 请查看按值传递与按参考传递以获取更多信息。
您的问题的解决方案是将您的原型更改为, void reverseList(node **head)
并且每次后续访问head
都必须使用*head
.
最后,调用你的函数reverseList(&head);
推荐阅读
- javascript - React Material-UI最简单的Hello Wold测试中的无效钩子调用错误
- encryption - 这种双挂锁类比与公私钥加密+签名之间是否有任何功能差异?
- java - JLabel上的透明背景GIF表现奇怪
- python - Performing for loop in pandas
- c# - System.ArgumentNullException:值不能为空 ASP.NET MVC5
- r - R。如何对名称中带有 () 括号的行进行子集化?
- visual-c++ - 与结构成员变量关联的对话框控件
- javascript - Highcharts - PieChart 在调用 this.setState 的点击事件上刷新
- c++ - 试图转换 wxVector 的一个组件
这是 wxString 到 wxStringArray 但程序不想 - python - 遍历 pandas 中的列,同时对每列应用不同的函数