思路

我的想法是先存到数组里面再比较,时间和空间复杂度都是O(N)
还有一种做法是翻转链表的前半段或者后半段,再使用两个指针进行滑动比较。

提交代码

class Solution {
    public boolean isPalindrome(ListNode head) {
        List<Integer> nums=new ArrayList<Integer>();
        ListNode p=head;
        while(p!=null){
            nums.add(p.val);
            p=p.next;
        }
        int num1,num2,p1=0,p2=nums.size()-1;
        while(p1<=p2){
            if(!nums.get(p1).equals(nums.get(p2)))  return false;
            p1++;p2--;
        }
            
        return true;
    }
}

运行结果

【leetcode】234(Easy)Palindrome Linked List

相关文章:

  • 2021-04-21
  • 2021-06-03
  • 2021-06-02
  • 2021-07-23
  • 2022-01-13
  • 2022-12-23
猜你喜欢
  • 2021-06-01
  • 2021-12-24
  • 2021-10-25
  • 2021-08-12
  • 2022-02-19
  • 2021-12-26
  • 2022-01-05
相关资源
相似解决方案