此博客链接:https://www.cnblogs.com/ping2yingshi/p/12715377.html
回文链表(93min)
题目链接:https://leetcode-cn.com/problems/palindrome-linked-list/
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
题解:
思路:
1.把整个链表存储在列表中。
2.把整个链表反转。
3.把列表中的数和反转的链表中的数判断是否相等。
链表反转请参考:https://www.cnblogs.com/ping2yingshi/p/12633556.html
代码如下:
class Solution { public boolean isPalindrome(ListNode head) { List<Integer> list = new LinkedList<Integer>(); // List<Integer> list = new LinkedList<Integer>(); ListNode pre=head; int count=0; while(pre!=null)//先存到集合中 { list.add(pre.val); pre=pre.next; count++; } // ListNode newhead=head; // ListNode next=head; ListNode new_head=null; while(head!=null)//反转链表 { ListNode temp=head; head=head.next; temp.next=new_head; new_head=temp; } int i=0; while(i<count-1&&new_head!=null)//反转后的链表和集合中的数字做比较 { if(new_head.val!=list.get(i)) { return false; } new_head=new_head.next; i++; } return true; } }