package Hot100;
import java.util.ArrayList;
import java.util.List;
/**
* leetcode HOT100 第234题 回文链表
* @author dengjie
* @create 2021-05-24 21:05
*/
public class Solution234 {
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(1);
ListNode node3 = new ListNode(2);
ListNode node4 = new ListNode(1);
// ListNode node5 = new ListNode(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
// node4.next = node5;
Solution234 solution234 = new Solution234();
boolean palindrome = solution234.isPalindrome(node1);
System.out.println(palindrome);
}
/**
* 方法一:先填入数组,再逐一比较
* @param head
* @return
*/
public boolean isPalindrome(ListNode head) {
if(head == null){
return false;
}
if(head.next == null){
return true;
}
List<Integer> list = new ArrayList<>();
while(head != null){
list.add(head.val);
head = head.next;
}
int i= 0, j = list.size() - 1;
while(i <= j){
if(list.get(i) != list.get(j)){
return false;
}
i++;
j--;
}
return true;
}
/**
* 方法二:快慢指针
* 整个流程可以分为以下五个步骤:
*
* 1.找到前半部分链表的尾节点。
* 2.反转后半部分链表。
* 3.判断是否回文。
* 4.恢复链表。
* 5.返回结果。
* @param head
* @return
*/
public boolean isPalindromeTwo(ListNode head) {
if (head == null) {
return true;
}
// 1.找到前半部分链表的尾节点并反转后半部分链表
ListNode firstHalfEnd = endOfFirstHalf(head);
ListNode secondHalfStart = reverseList(firstHalfEnd.next);
// 2.判断是否回文
ListNode p1 = head;
ListNode p2 = secondHalfStart;
boolean result = true;
while (result && p2 != null) {
if (p1.val != p2.val) {
result = false;
}
p1 = p1.next;
p2 = p2.next;
}
// 还原链表并返回结果
firstHalfEnd.next = reverseList(secondHalfStart);
return result;
}
private ListNode reverseList(ListNode head) {
//反转链表
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
private ListNode endOfFirstHalf(ListNode head) {
//快慢指针找到中间节点
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
//**************************************************************
/**
* 方法三:递归
* @param head
* @return
*/
public boolean isPalindromeThree(ListNode head) {
frontPointer = head;
return recursivelyCheck(head);
}
private ListNode frontPointer;
private boolean recursivelyCheck(ListNode currentNode) {
if (currentNode != null) {
if (!recursivelyCheck(currentNode.next)) {
return false;
}
if (currentNode.val != frontPointer.val) {
return false;
}
frontPointer = frontPointer.next;
}
return true;
}
}
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
", next=" + next +
'}';
}
}
【leetcode】HOT100第234题:回文链表
最新推荐文章于 2024-08-11 19:53:56 发布