关闭

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

108人阅读 评论(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;
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:296次
    • 积分:22
    • 等级:
    • 排名:千里之外
    • 原创:2篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档