链表的回文结构 C语音

链表的回文结构_牛客题霸_牛客网 (nowcoder.com)   (点击前面链接即可查看题目)

reverseList函数请参考:反转链表 - 力扣(LeetCode)C语言-CSDN博客

middleNode函数请参考:链表的中间结点 - 力扣(LeetCode)C语言-CSDN博客

链表:1->2->3->2->1

        先找到中间结点, 也就是3,然后反转3->2->1,但是要注意标红的2仍旧指向3,

所以链表变成了1->2->3<-2<-1,就成了这样.

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
  public:
    struct ListNode* reverseList(struct ListNode* head) {
        if (head == NULL)
            return NULL;
        else {
            struct ListNode* oldhead = head;
            struct ListNode* newhead = NULL;
            while (oldhead) {
                struct ListNode* nextnode = oldhead->next;
                oldhead->next = newhead;
                newhead = oldhead;
                //迭代
                oldhead = nextnode;
            }
            return newhead;
        }
    }
    struct ListNode* middleNode(struct ListNode* head) {
        struct ListNode* slow = head;
        struct ListNode* fast = head;
        //空指针
        if (NULL == head) {
            return NULL;
        }
        //一个结点
        else if (NULL == head->next) {
            return head;
        }
        //大于等于2个结点
        else {
            while (fast) {
                if (NULL == fast->next) {
                    return slow;
                }
                slow = slow->next;
                fast = fast->next->next;
            }
            return slow;
        }
    }
    bool chkPalindrome(ListNode* A) 
    {
        // write code here
        ListNode* mid = middleNode(A);
        ListNode* rmid = reverseList(mid);
        while(rmid)
        {
            if(rmid->val != A->val)
            {
                return false;
            }
            else
            {
                rmid = rmid->next;
                A = A->next; 
            }
        }
        return true;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值