力扣简234 回文列表


1 public static boolean isPalindrome(ListNode head) { 2 List<Integer> list=new ArrayList<Integer>(); 3 int num=0; 4 while(head!=null) { 5 list.add(head.val); 6 head=head.next; 7 num++; 8 } 9 for(int i=0,j=num-1;i<=j;i++,j--) { 10 if(list.get(i)!=list.get(j)) { 11 return false; 12 } 13 } 14 return true; 15 } 16
题解2:递归
没写
题解三:运用快慢指针找到中间位置,将后半部分反转进行比较,记得最后要反转回原来的链表。

public static boolean isPalindrome(ListNode head) { if(head==null) { return true; } ListNode temp=head; ListNode reverseNode=findMidNode(head); ListNode reverse=reverseList(reverseNode.next); ListNode temp2=reverse; while(temp2!=null) { if(temp.val!=temp2.val) { return false; } else{ temp=temp.next; temp2=temp2.next; } } reverseNode.next=reverseList(reverse); return true; } //自己写一下递归反转 浪费半天时间没写出来个啥哈哈哈 说明要复习 写了一堆也没用 public static ListNode reverseList(ListNode head) { ListNode pre=null; ListNode now=null; while(head!=null) { now=head; head=head.next; now.next=pre; pre=now; } return now; } public static ListNode findMidNode(ListNode head) { ListNode slow=head; ListNode fast=head; while((fast.next!=null)&&fast.next.next!=null) { fast=fast.next.next; slow=slow.next; } return slow; }

浙公网安备 33010602011771号