反转一个字符串或链表(栈实现)

为了节省篇幅,用c++中的#include < stack >实现栈。

补充一下#include < stack >的成员函数:

 PS:定义一个栈:

stack< typename > name ; 

反转一个字符串:

#include<iostream>
#include<string>
#include<stack>
using namespace std;

void reverse(char c[], int n)
{
	int i;
	stack<char> S;
	for (i = 0;i < n;i++)//把字符压入栈
	{
		S.push(c[i])  ;
	}
	for (i = 0;i < n;i++)//把字符输出(从顶部开始)并赋值给c[i]。
	{
		c[i] = S.top();
		S.pop();
	}
}
int main()
{
	char c[51];
	cout << "输入一串字符:" << endl;
	cin >> c;
	reverse(c, strlen(c));
	cout << "反转后的字符:" << endl;
	puts(c);
}

 反转一个链表:

#include<iostream>
#include<string>
#include<stack>
using namespace std;

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

sn* head = NULL;

void insert(int x)
{
	sn* temp = new sn;
	temp->data = x;
	temp->next = head;
	head = temp;
}
void print()
{
	sn* temp = new sn;
	temp = head;
	cout << "链表现在是:";
	while (temp != NULL)
	{
		cout << temp->data << " ";
		temp = temp->next;
	}
	cout << endl;
}
void reverse()
{
	if (head == NULL)//链表为空
		return;
	stack<sn*> S;//创建栈
	sn* temp = head;
	while (temp != NULL)//遍历链表压入栈
	{
		S.push(temp);
		temp = temp->next;
	}
	temp = S.top();//重置temp指向栈顶
	head = temp;//重置head指向栈顶
	S.pop();//输出栈顶元素
	while (!S.empty())//当栈非空遍历链表输出栈顶元素
	{
		temp->next = S.top();
		S.pop();
		temp = temp->next;
	}
	temp->next = NULL;
}
int main()
{
	insert(2);print();
	insert(4);print();
	insert(6);print();
	insert(8);print();
	reverse();print();
}

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xxx_xiyuyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值