leetcode234

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public bool IsPalindrome(ListNode head) {
        if (head == null)
            {
                return true;
            }
            else
            {
                Queue<int> Q = new Queue<int>();
                Stack<int> S = new Stack<int>();

                do
                {
                    Q.Enqueue(head.val);
                    S.Push(head.val);

                    head = head.next;
                }
                while (head != null);

                var len = S.Count;

                for (int i = 0; i < len; i++)
                {
                    var s = S.Pop();
                    var q = Q.Dequeue();
                    if (s != q)
                    {
                        return false;
                    }
                }
                return true;
            }
    }
}

https://leetcode.com/problems/palindrome-linked-list/#/description

时间: 2024-12-14 04:31:33

leetcode234的相关文章

LeetCode234——Palindrome Linked List,O(n) time and O(1) space

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? 实现: bool isPalindrome(ListNode* head) { if (head == NULL || head->next == NULL) return true; ListNode* beg = head, *end = head; while

LeetCode234: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)的空间复杂度内求解.如果没有时间复杂度的限制,可以直接将链表反转再比较就可以了.但是这样时间复杂度和空间复杂度都是O(n). 想了很久都没想明白,虽然这是道easy的题目,看了Discuss

LeetCode链表解题模板

一.通用方法以及题目分类 0.遍历链表 方法代码如下,head可以为空: ListNode* p = head; while(p!=NULL) p = p->next; 可以在这个代码上进行修改,比如要计算链表的长度: ListNode* p = head; int num = 0; while(p!=NULL){ num++; p = p->next; } 如果要找到最后的节点,可以更改while循环中的条件,只不过需要加上head为NULL时的判断 if(!head) return hea