【链表】判断单链表是否是回文链表

1 篇文章 0 订阅
1 篇文章 0 订阅

题目来源:leetcode

Question: 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?

首先回文链表是什么意思?

是指,链表的逆序和正序一模一样。

例: {5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5}是回文序列


代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {     //in O(n) time and O(1) space
        if (head == NULL || head->next == NULL) //空链表或单节点链表
        {
            return true;     
        }
		
		bool result = false;
		
	    int listLen = 0;
		for (ListNode *pNode = head; pNode != NULL; pNode = pNode->next)
		{
		    ++listLen;
		}
		
		ListNode *pPre = NULL;
		ListNode *pCur = head;
		ListNode *pNext = head->next;
		
		for (int i=0; i<listLen/2; ++i) //一分为二,左边链表逆序,右边链表不变
		{
		    pCur->next = pPre;
		    pPre = pCur;
		    pCur = pNext;
		    pNext = pNext->next;
		}
		
		ListNode *pLeftHead = pPre;
		ListNode *pRightHead = pCur;
		if (listLen & 1) //若是奇数,不比较中间数
		{
		    pRightHead = pRightHead->next;
		}
		
		while (pLeftHead != NULL)   //左右链表逐个遍历,如果全部相等,才是回文
		{
		    if(pLeftHead->val != pRightHead->val)
		    {
		        result = false;
		        break;
		    }
		    pLeftHead = pLeftHead->next;
		    pRightHead = pRightHead->next;
		}
		if (pLeftHead == NULL)
		{
		    result = true;
		}
		
		//还原链表结构
		pLeftHead = pPre;
		pRightHead = pCur;
		pPre = pRightHead;
		pCur = pLeftHead;
		pNext = pLeftHead->next;
		for (int i=0; i<listLen/2; ++i)
		{
		    pCur->next = pPre;
		    pPre = pCur;
		    pCur = pNext;
		    if (pNext != NULL)
		    {
		        pNext = pNext->next;
		    }
		}
		
		return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值