LeetCode | 234. 回文链表

简介: LeetCode | 234. 回文链表

LeetCode | 234. 回文链表

O链接


  • 这里的解法是先找到中间结点
  • 然后再将中间节点后面的节点逆序一下
  • 然后再从头开始和从中间开始挨个比较
  • 如果中间开始的指针到走最后都相等,就返回true,否则返回false

代码如下:

struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode* n1,*n2,*n3;
    if(head == NULL)
        return NULL;
    n1 = NULL,n2 = head;n3 = n2->next;
    while(n2)
    {
        n2->next = n1;
        n1 = n2;
        n2 = n3;
        if(n3)
            n3 = n3->next; 
    }
    return n1;
}
struct ListNode* middleNode(struct ListNode* head) {
    struct ListNode* slow = head,*fast = head;
    while(slow && slow->next)
    {
        slow = slow->next->next;
        fast = fast->next;
    }
    return fast;
}
bool isPalindrome(struct ListNode* head) {
    struct ListNode* mid = middleNode(head);
    struct ListNode* rhead = reverseList(mid);
    while(head&&rhead)
    {
        if(head->val == rhead->val)
        {
            head = head->next;
            rhead = rhead->next;
        }
        else
        {
            return false;
        }
    }
    return true;
}
相关文章
|
2天前
LeetCode链表hard 有思路?但写不出来?
LeetCode链表hard 有思路?但写不出来?
|
2天前
|
索引
每日一题:力扣328. 奇偶链表
每日一题:力扣328. 奇偶链表
13 4
|
2天前
leetcode代码记录(移除链表元素
leetcode代码记录(移除链表元素
10 0
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——链表的中间结点
【每日一题】LeetCode——链表的中间结点
|
2天前
|
C++
[leetcode 链表] 反转链表 vs 链表相交
[leetcode 链表] 反转链表 vs 链表相交
|
2天前
【力扣】148. 排序链表
【力扣】148. 排序链表
|
2天前
|
索引
【力扣】142. 环形链表 II
【力扣】142. 环形链表 II
|
2天前
【力扣】19. 删除链表的倒数第 N 个结点
【力扣】19. 删除链表的倒数第 N 个结点
|
2天前
|
算法
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)

热门文章

最新文章