回文链表

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?


第一种方法就是直接使用一个List把链表转成数组

第二种就是可以简单的把链表进行翻转然后进行比较:

 /// <summary>
        /// 将链表复制一份并进行反转,可做优化比较顺序减半
        /// </summary>
        /// <param name="head"></param>
        /// <returns></returns>
        public static bool Method2(ListNode head)
        {
            if (head == null) return true;
            //创建一个倒序的链表
            ListNode node = head;
            ListNode tmp = null;
            while (node != null)
            {
                ListNode tmpNode = new ListNode(node.val);
                tmpNode.next = tmp;
                tmp = tmpNode;
                node = node.next;
            }
            //比对原链表与逆序链表是否一致
            while (tmp != null)
            {
                if (tmp.val != head.val)
                {
                    return false;
                }
                head = head.next;
                tmp = tmp.next;
            }
            return true;
        }

第三种我也是查找网上的方法找到的使用递归,方法比较巧妙值得学习奋斗

private static ListNode tmp;
        /// <summary>
        /// 递归调用
        /// </summary>
        /// <param name="head"></param>
        /// <returns></returns>
        public static bool Method3(ListNode head)
        {
            tmp = head;
            return IsPalindrome(head);
        }

        private static bool IsPalindrome(ListNode head)
        {
            if (head == null) return true;
            bool result = IsPalindrome(head.next) && (tmp.val == head.val);
            tmp = tmp.next;
            return result;
        }









猜你喜欢

转载自blog.csdn.net/u012371712/article/details/81014720