LeetCode每日一题:回文链表(No.234)

栏目: 数据库 · 发布时间: 7年前

输入: 1->2
输出: false

输入: 1->2->2->1
输出: true
复制代码

思考:

先用快慢指针找到链表中间节点,再将之后的链表反转,反转之后与前半链表节点比较。
复制代码

实现:

class Solution {
public boolean isPalindrome(ListNode head) {
    ListNode slow = head;
    ListNode quick = head;
    while (quick != null && quick.next != null) {
        slow = slow.next;
        quick = quick.next.next;
    }
    ListNode half = slow;
    ListNode reverse = reverse(half);
    while (reverse != null) {
        if (head.val == reverse.val) {
            head = head.next;
            reverse = reverse.next;
        } else {
            return false;
        }
    }
    return true;
}
 public static ListNode reverse(ListNode head) {
    ListNode pre = null;
    ListNode cur = head;
    while (cur != null) {
        ListNode temp = cur.next;
        cur.next = pre;
        pre = cur;
        cur = temp;
    }
    return pre;
}
}复制代码

以上所述就是小编给大家介绍的《LeetCode每日一题:回文链表(No.234)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Natural Language Processing with Python

Natural Language Processing with Python

Steven Bird、Ewan Klein、Edward Loper / O'Reilly Media / 2009-7-10 / USD 44.99

This book offers a highly accessible introduction to Natural Language Processing, the field that underpins a variety of language technologies, ranging from predictive text and email filtering to autom......一起来看看 《Natural Language Processing with Python》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具