class Node
{
public:
int data;
Node * next;
public:
Node(int x)
{
data = x;
next = NULL;
}
};
//栈的类定义
class stack
{
public:
Node * first;
int size;
public:
stack() //初始化栈
{
first = NULL;
size = 0;
}
void push(const int a)
{
if (first == NULL)
{
first = new Node(a);
size = size + 1;
}
else
{
Node * p = new Node(a);
p->next = first;
first = p;
size = size + 1;
}
}
void pop(int & item)
{
if (size == 0)
{
cout << "栈为空,不能进行出栈操作" << endl;
}
else
{
item = first->data;
Node *temp = first->next;
delete first;
first = temp;
size--;
}
}
};
class listNode
{
public:
Node * first;
Node *tail;
int length;
public:
listNode() //初始化链表
{
first =tail= NULL;
length = 0;
}
void inlistNode(int x) //简单的在链表末尾添加元素
{
if (first == NULL)
{
first =tail= new Node(x);
length++;
}
else
{
tail->next = new Node(x);
tail = tail->next;
length++;
}
}
void inverse() //倒置算法
{
stack R;
int i = 0;
Node * temp = first;
for (i; i < length; i++)
{
R.push(temp->data);
temp = temp->next;
}
temp = first;
for (i = 0; i < length; i++)
{
R.pop(temp->data);
temp = temp->next;
}
}
};
利用栈的倒置算法
最新推荐文章于 2022-10-08 15:28:15 发布