采用顺序栈的回文判断
栈是一种后进先出(LIFO)的线性表,限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。 下面给出顺序栈的操作实现
顺序栈
#pragma once
template <class ElemType>
class SqStack {
public:
SqStack(int m
);
~SqStack();
void Clear();
bool Empty() const;
int Length() const;
ElemType
& Top() const;
void Push(const ElemType
& e
);
void Pop();
private:
ElemType
* m_base
;
int m_top
;
int m_size
;
};
template<class ElemType>
SqStack
<ElemType
>::SqStack(int m
)
{
m_top
= 0;
m_base
= new ElemType
[m
];
m_size
= m
;
}
template<class ElemType>
SqStack
<ElemType
>::~SqStack()
{
if (m_base
!= NULL)
delete[] m_base
;
}
template<class ElemType>
void SqStack
<ElemType
>::Clear()
{
m_top
= 0;
}
template<class ElemType>
bool SqStack
<ElemType
>::Empty() const
{
return m_top
== 0;
}
template<class ElemType>
int SqStack
<ElemType
>::Length() const
{
return m_top
;
}
template<class ElemType>
ElemType
& SqStack
<ElemType
>::Top() const
{
return m_base
[m_top
- 1];
}
template<class ElemType>
void SqStack
<ElemType
>::Push(const ElemType
& e
)
{
if (m_top
>= m_size
) {
ElemType
* newbase
;
newbase
= new ElemType
[m_size
+ 10];
for (int i
= 0; i
< m_top
; i
++)
newbase
[i
] = m_base
[i
];
delete[] m_base
;
m_base
= newbase
;
m_size
+= 10;
}
m_base
[m_top
++] = e
;
}
template<class ElemType>
void SqStack
<ElemType
>::Pop()
{
m_top
--;
}
显然,上述顺序栈的操作中,时间复杂度均为o(1)。
顺序栈的应用:回文判断
算法描述不再赘述。
#include <iostream>
#include "SqStack.h"
using namespace std
;
#define MAX_STRING_LEN 100
bool ispalindrome(char* in_string
) {
SqStack
<char> s(MAX_STRING_LEN
);
char deblankstring
[MAX_STRING_LEN
], c
;
int i
= 0;
while (*in_string
!= '\0')
{
if (*in_string
!= ' ')
deblankstring
[i
++] = *in_string
;
in_string
++;
}
deblankstring
[i
] = '\0';
i
= 0;
while (deblankstring
!='\0')
{
s
.Push(deblankstring
[i
++]);
}
i
= 0;
while (!s
.Empty())
{
c
= s
.Top();
s
.Pop();
if (c
!= deblankstring
[i
])
return false;
i
++;
}
return true;
}
int main()
{
char instring
[MAX_STRING_LEN
];
cout
<< "请输入一个字符串:" << endl
;
cin
.get(instring
, MAX_STRING_LEN
);
if (ispalindrome(instring
))
cout
<< "\"" << instring
<< "\"" << "是回文。" << endl
;
else
cout
<< "\"" << instring
<< "\"" << "不是回文。" << endl
;
system("pause");
return 0;
}