判断单链表是否为回文链表
(牛客网—牛客题霸算法篇—NC96)
题目描述
给定一个链表,请判断该链表是否为回文结构。
回文是指该字符串正序逆序完全一致。
思路
Java实现
方法一:遍历
定义三个指针,分别为left、right和move,left指向链表前半部分的当前要比较的节点,right指向后半部分的当前要比较的节点,由于单链表不能寻找前一节点,使用move指针寻找right节点。
优点:简单容易理解
缺点:时间耗费较多,只适合于较短的链表。
方法二:栈
栈是一种先进后出的数据结构,我们把链表中的数据全部存入到栈中,这样依次出栈时就相当于逆序访问链表了。
在存入数据时,可以顺便计算链表的长度,这样在出栈比较时就只需要比较一般的数据,更加节省时间。
代码实现
方法一:暴力遍历
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
public boolean isPail (ListNode head) {
// write code here
if(head==null||head.next==null){
return true;
}
int n=1;
ListNode left=head;
ListNode right=head;
ListNode move=head;
while(move.next!=null){
n++;
move=move.next;
}
right=move;
for(int i=0;i<n/2;i++){
move=left;
if(left.val!=right.val){
return false;
}
while(move.next!=right){
move=move.next;
}
left=left.next;
right=move;
}
return true;
}
}
方法二:使用栈
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
public boolean isPail (ListNode head) {
// write code here
if(head==null||head.next==null){
return true;
}
ListNode list=head;
Stack<Integer> stack=new Stack();
int len =0;
while(list!=null){
stack.push(list.val);
list=list.next;
len++;
}
len=len/2;
while(len>=0){
if(head.val!=stack.pop()){
return false;
}
head=head.next;
len--;
}
return true;
}
}