234. 回文链表

  • 思路
  1. 找到链表的中间节点
  2. 将以中间节点作为链表的首节点进行反转
  3. 比较两个链表是否相等(如果是奇数,cur2比cur1多一个节点,此时注意玄幻条件以cur1为准即可)
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution 
{
public:
	// 反转链表
    ListNode* reverseList(ListNode* head) 
	{
        ListNode* temp; // 保存cur的下一个节点
        ListNode* cur = head;
        ListNode* pre = nullptr;
        while(cur) 
		{
            temp = cur->next;  // 保存一下 cur的下一个节点,因为接下来要改变cur->next
            cur->next = pre; // 翻转操作
            // 更新pre 和 cur指针
            pre = cur;
            cur = temp;
        }
        return pre;
    }
	bool isPalindrome(ListNode* head) 
    {
		if(head == nullptr || head->next == nullptr)
		{
			return true;
		}

		ListNode* pre = head;
		ListNode* slow = head;	
		ListNode* fast = head;

		while(fast && fast->next)//找到链表的中间节点
		{
			pre = slow;
			slow = slow->next;
			fast = fast->next->next;
		}
		pre->next = nullptr; // 分割链表
		ListNode* cur1 = head;  // 前半部分
        ListNode* cur2 = reverseList(slow); // 反转后半部分,总链表长度如果是奇数,cur2比cur1多一个节点

		// 开始两个链表的比较	
		while(cur1)
		{
			if(cur1->val != cur2->val)
			{
				return false;
			}
			cur1 = cur1->next;
			cur2 = cur2->next;
		}
		
		return true;
    }
};```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值