思路1:遍历一次链表,用一个数组存储链表节点值,然后用双指针法判断数组是否是回文的。需要额外O(n)的空间。 C++ classSolution{public:boolisPalindrome(ListNode* head){if(!head || !head->next)returntrue; vector<int> vec;while(head) { vec.push_back(head->val); head = head->next; }for(inti ...
然后把前半截的node values逐个push到一个stack里。然后从后半截开始逐个比较node value和stack[-1]。注意list长度为奇偶的两种情况。奇数时,先pop掉中间一个。 1classSolution(object):2defisPalindrome(self, head):3"""4:type head: ListNode5:rtype: bool6"""7ifnotheadornothead.next:8returnTrue910m ...
Can you solve this real interview question? Palindrome Linked List - Given the head of a singly linked list, return true if it is a palindrome or false otherwise. Example 1: [https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg] Inpu
[Leetcode] Palindrome Linked List 回文链表 Palindrome Linked List Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) time and O(1) space? 反转链表 复杂度 时间O(N) 空间 O(1) 思路 两个指针都从头出发,快指针每次两步,慢指针每次一步,这样快...
LeetCode: 234. Palindrome Linked List 题目描述 Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false 1. 2. Example 2: Input: 1->2->2->1 Output: true 1. 2. Follow up: Could you do it in O(n) time and ...
【LeetCode】234 Palindrome Linked List Total Accepted: 1116 Total Submissions: 4295 My Submissions Question Solution Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) time and O(1) space?
My code: importjava.util.Stack;/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */publicclassSolution{publicbooleanisPalindrome(ListNode head){if(head==null||head.next==null)returntrue;ListNode slow=...
234. Palindrome Linked List 开始April的daily leetcode。 直接考虑O(n)时间 O(1)空间的做法,假设允许改动List nodes。 容易想到用双指针去跑,这样可以找到中点。在跑的过程中将前半截reverse一下。然后两个指针分别往两边不断next比较。 可以自己画图观察,例如3个节点的list,第一次p跑到1,q跑到2;第二次q在...
Leetcode-Easy 234. Palindrome Linked List 描述: 判断一个单链表是否左右对称 代码语言: 代码运行次数: # Definitionforsingly-linked list.#classListNode:# def__init__(self,x):# self.val=x # self.next=NoneclassSolution(object):defisPalindrome(self,head):""":type head:ListNode:rtype:bool"""...
LeetCode problem solving notes. Determine whether a linked list is a palindrome linked list. First convert the linked list into an array, and then judge whether the array is a palindrome array.