地址:https://leetcode-cn.com/problems/palindrome-linked-list/
解法一:
---------算法:
(1):声明List集合
(2):循环链表,将链表中的数据存入list集合中
(3):声明首尾指针,进行判断首尾两个元素是否相同,不同,返回false,否则,返回true
//定义单链表
public class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int val){this.val=val;}
ListNode(int val,ListNode next){this.val=val;this.next=next;}
}
class Solution{
public boolean isPalindrome(ListNode head){
List<Integer> list=new ArrayList<Integer>();
//将链表中的数据放到list集合中
ListNode cur=head;
while(cur!=null){
list.add(cur.val);
cur=cur.next;
}
//声明首尾指针
int front=0;
int back=list.size()-1;
while(front<back){
if(!(list.get(front)).equals(list.get(back))){
return false;
}
front++;
back--;
}
return true;
}
}
解法二:使用快慢指针加反转单链表
算法:1、使用快慢指针找到单链表的中点
首先,我们设置两个指针slow和fast,slow指针每次移动一步,fast指针每次移动两步;如果链表中节点个数为偶数时,当快指针无法移动时,慢指针刚好指向中点;如果链表中节点个数为奇数时,当快指针走完,慢指针指向中点前一个节点
2、从中间节点反转单链表
3、将反转后的单链表于原链表的前半部分进行比较
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
//解法一
// List<Integer> list=new ArrayList<Integer>();
// //将链表中的数据放到list集合中
// ListNode cur=head;
// while(cur!=null){
// list.add(cur.val);
// cur=cur.next;
// }
// //声明首尾指针
// int front=0;
// int back=list.size()-1;
// //循环
// while(front<back){
// if(!(list.get(front)).equals(list.get(back))){
// return false;
// }
// front++;
// back--;
// }
// return true;
//解法二
//声明快慢指针
ListNode fast=head;
ListNode slow=head;
//寻找链表的中间节点
while(fast!=null && fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
//如果fast不为空,则说明链表的长度为奇数,slow节点在中间节点的前一个位置
if(fast!=null){
slow=slow.next;
}
//反转后的单链表
ListNode slow1=reverseLink(slow);
ListNode cur=head;
//比较
while(slow1!=null){
//判断链表值大小是否相等
if(slow1.val!=cur.val){
return false;
}
slow1=slow1.next;
cur=cur.next;
}
return true;
}
//反转单链表
private ListNode reverseLink(ListNode head){
ListNode prev=null;
while(head!=null){
ListNode next=head.next;
head.next=prev;
prev=head;
head=next;
}
return prev;
}
}
解法三:使用栈解决
栈是先进后出的数据结构,将链表的节点全部放到栈中,然后再一个一个出栈与原链表进行比较,这就相当于从后往前访问链表了。
public boolean isPalindrome(ListNode head){
ListNode temp=head;
Stack<Integer> stack=new Stack<>();
//把链表节点的值存放到栈中
while(temp!=null){
stack.push(temp.val);
temp=temp.next;
}
//出栈和原链表进行比较
while(head!=null){
if(head.val!=stack.pop()){
return false;
}
head=head.next;
}
return true;
}