本文主要是介绍【注释详细,思路清晰】【打卡第17天】leetcode热题HOT100之Java实现:234. 回文链表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、题目描述
请判断一个链表是否为回文链表。
2、题目分析
什么是回文链表?
示例1不是回文链表,[1,2],并不对称
示例2是回文链表,[1,2,2,1],是整个集合是对称的。
3、代码实现
整个代码实现也非常简单。
一部分是将链表中的值存储到集合List中。
另一部分判断List集合中的首尾元素是否相等。
/*** 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; }* }*//**定义一个List集合存储链表中的结点,只需要判断收尾位置的结点,是否对称值是否相等*/
class Solution {public boolean isPalindrome(ListNode head) {//定义List集合存储链表元素List<Integer> list = new ArrayList<>();while(head != null){list.add(head.val);head = head.next;}// 判断List是否对称// List集合的元素首位置int startIndex = 0;// List集合的尾元素位置int endIndex = list.size() - 1;while(startIndex < endIndex){if(! list.get(startIndex).equals(list.get(endIndex))){return false;}startIndex++;endIndex--;}return true;}
}
加油!
这篇关于【注释详细,思路清晰】【打卡第17天】leetcode热题HOT100之Java实现:234. 回文链表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!