题解 | #链表的回文结构#

链表的回文结构

https://www.nowcoder.com/practice/d281619e4b3e4a60a2cc66ea32855bfa

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
#include<iostream>
using namespace std;
struct ListNode* MidNode(struct ListNode* phead)
{
	struct ListNode* fast, * slow;
	slow=fast =phead; 
	while (fast && fast->next)
	{
		fast = fast->next->next;
		slow = slow->next;
	}
	return slow;
}
struct ListNode* reverseList(struct ListNode* phead)
{
	struct ListNode* newhead = NULL;
	struct ListNode* cur = phead;
	struct ListNode* next = cur->next;

	while (cur)
	{
		next = cur->next;
		cur->next = newhead;
		newhead = cur;
		cur = next;
	}
	return newhead;
}

class PalindromeList {
public:
	bool chkPalindrome(struct ListNode* A) {

		ListNode* phead = A;
            ListNode* mid = MidNode(phead);
            ListNode* newphead = reverseList(mid);
            ListNode* p1 = phead;
            ListNode* p2 = newphead;
            while (p2 && p1) 
            {
                if (p1->val != p2->val) 
                {
                    return false;
                }
                p1 = p1->next;
                p2 = p2->next;
            }
            return true;
	}
};





全部评论

相关推荐

挣K存W养DOG:我记得好多人说这个公司就是白嫖方案的,现在有大体方案要让你给他展示实现细节了,也是无敌了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务