为了节省篇幅,用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();
}