Palindrome Linked List 综合了反转链表和快慢指针的解法 这道题容易想到的思路是:遍历链表存入list中,判断list是否回文 但综合类解法为:用快慢指针找到链表的中间位置,然后将链表从中间断开,将后半部分翻转,与前半部分比较。 classSolution {publicbooleanisPalindrome(ListNode head) { List<
https://leetcode.com/problems/palindrome-linked-list/ 思路1:遍历一次链表,用一个数组存储链表节点值,然后用双指针法判断数组是否是回文的。需要额外O(n)的空间。 C++ classSolution{public:boolisPalindrome(ListNode* head){if(!head || !head->next)returntrue; vector<int> vec;while(head) { vec.push...
AI代码解释 classSolution{publicbooleanisPalindrome(ListNode head){ListNode fast=head;ListNode slow=head;if(fast==null||fast.next==null)returntrue;while(fast.next!=null&&fast.next.next!=null){fast=fast.next.next;slow=slow.next;}ListNode newHead=reverseList(slow.next);while(newHead!=null){if(...
* Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: //判断链表是否是回文:逆转比较,入栈比较; bool isPalindrome(ListNode* head) { stack<ListNode *> s; if(head==NULL)...
* Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { if(head == NULL || head->next == NULL) return true; ...
Solution2: space=o(1) /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution{public:boolisPalindrome(ListNode*head){if(NULL==head||NULL==head->next)returntrue;ListNode*fast=he...
可以自己画图观察,例如3个节点的list,第一次p跑到1,q跑到2;第二次q在第一小步就越界了(q每次移动2位),说明list长度是奇数。同理第二小步越界的话,说明长度是偶数。 自己举几个例子观察,可以得出p,q应该指向的位置。 classSolution:defisPalindrome(self,head:ListNode)->bool:# find mid node firstp,q=hea...
Solution Analysis: First convert the linked list into an array, and then judge whether the array is a palindrome array Loop this array to determine whether the values after moving the same distance from the start and end positions are the same. If they are all the same, the result is a ...
Approach 3(Using stack) For Palindrome Linked List: A simple solution is to use a stack of list nodes. This mainly involves three steps.Traverse the given list from head to tail and push every visited node to stack.Traverse the list again. For every visited node, pop a node from the st...
class Solution { public boolean isPalindrome(ListNode head) { ListNode fast = head, slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } if (fast != null) { slow = slow.next; } slow = reverseList(slow); fast = head; while ...