问题描述:
判断链表是否为回文链表
思路分析:
利用快慢指针和栈进行判断,慢指针走k步,快指针走2k步,在此过程中利用栈结构进行入栈操作,然后步进慢指针,将其值与弹出的栈的数据进行比对即可判断。
代码见下:
package List;
import java.util.Stack;
class Node1{
Object data;
Node1 next;
public Node1(Object data) {
this.data = data;
}
}
public class Hwlb {
//回文链表
public static boolean check(Node1 first)
{
Node1 s=first;//慢指针
Node1 f=first;//快指针
Stack<Node1> stack=new Stack<>();//建立栈
while (f==null||f.next==null)//应对奇数和偶数的情况
{
stack.push(s);//数据入栈
s=s.next;//步进为一
f=f.next.next;//步进为二
}
while (s!=null)
{
s=s.next;
if (!stack.empty()) {
if (s.data != stack.pop().data)//出栈比对数据
return false;
}
}
return true;
}
public static void main(String[] args) {
Node1 node1=new Node1("a");
node1.next=new Node1("b");
node1.next.next=new Node1("c");
node1.next.next.next=new Node1("c");
node1.next.next.next.next=new Node1("b");
node1.next.next.next.next.next=new Node1("a");
System.out.println(check(node1));
}
}
运行结果见下: