链栈判断是否回文
1.定义节点类
代码如下(示例):
public class LinkNode<Object> {
Object data;
LinkNode<Object> next;
public LinkNode()
{
next=null;
}
public LinkNode(Object d)
{
data=d;
next=null;
}
}
2.定义链栈及基本运算的实现
代码如下(示例):
public class LinkStackClass<Object> {
LinkNode<Object> head;
public LinkStackClass()
{
head=new LinkNode<Object>();
head.next=null;
}
public boolean empty()
{
return head.next==null;
}
public void push(Object e)
{
LinkNode<Object> s=new LinkNode<Object>(e);
s.next=head.next;
head.next=s;
}
public Object pop()
{
if(empty())
throw new IllegalArgumentException("栈空");
Object e= head.next.data;
head.next=head.next.next;
return e;
}
public Object peek()
{
if(empty())
throw new IllegalArgumentException("栈空");
Object e=head.next.data;
return e;
}
}
3.判断是否是回文
将字符串str的前半部分依次进栈,后再连续出栈并于str字符串的后半部分比较,若·前半部分的反向序列与后半部分相同则是回文。
import java.util.*;
public class 应用二 {
public static boolean isPalindrome(String str)
{
LinkStackClass<Object> st=new LinkStackClass<Object>();
int n=str.length();
int i=0;
while(i<n/2)
{
st.push(str.charAt(i));
i++;
}
if(n%2==1)
i++;
while(i<n)
{
if((char)st.pop()!=str.charAt(i))
return false;
i++;
}
return true;
}
public static void main(String[] args)
{
System.out.println("测试");
Scanner sc=new Scanner(System.in);
while(sc.hasNext())
{
String str=sc.nextLine();
if(isPalindrome(str)) System.out.println("是回文");
else System.out.println("不是回文");
}
}
}