Leetcode Hot 100刷题记录 -Day19(回文链表)
回文链表
问题描述:
给你一个单链表的头节点
head
,请你判断该链表是否为回文链表。如果是,返回true
;否则,返回false
。示例 1:
输入:head = [1,2,2,1] 输出:true示例 2:
输入:head = [1,2] 输出:false解题思路:
将链表的值复制到数组列表中,再使用双指针法判断。
//提交版/*** 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<>();ListNode curr = head;while (curr != null){list.add(curr.val);curr = curr.next;}int a = 0;int b = list.size()-1;while (a<b){if (list.get(a) != list.get(b))return false;a++;b--;}return true;}
}//带有输入输出
import dto.ListNode;import java.util.ArrayList;
import java.util.List;public class hot_19isPalindrome {public boolean isPalindrome(ListNode head){List<Integer> list = new ArrayList<>();ListNode curr = head;while (curr != null){list.add(curr.val);curr = curr.next;}int a = 0;int b = list.size()-1;while (a<b){if (list.get(a) != list.get(b))return false;a++;b--;}return true;}public static void main(String[] args) {ListNode headA = new ListNode(1);headA.next = new ListNode(2);headA.next.next = new ListNode(2);headA.next.next.next = new ListNode(1);hot_19isPalindrome hot19isPalindrome = new hot_19isPalindrome();boolean result = hot19isPalindrome.isPalindrome(headA);System.out.println("输出:" + result);}
}