高频笔试题_栈和队列

回文链表
用到了之前学到的知识,先用快慢指针分割链表,然后反转第二段链表,将前一段链表与这一段链表的值一个一个相比,如果不同直接return false,否则继续遍历,直到遍历完其中一个链表,return true
判端条件:while(head1 && head2)
这道题真的是折磨,写了这么久的链表,被这道题给整不会了,花了半个小时,不停的写函数,调用函数,太离谱了,这真的是简单题

/**
 * 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* reverse(ListNode* head) {
        //反转这段链表
        ListNode* temp = nullptr;
        ListNode* pre = nullptr;
        ListNode* cur = head;
        while(cur) {
            temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
    //计算链表大小的函数
    int sizeofList(ListNode* head) {
        int size = 0;
        while(head) {
            size++;
            head = head->next;
        }
        return size;
    }
    //判断链表是否是回文链表
    bool isPalindrome(ListNode* head) {
        int size = sizeofList(head);
        if(size == 0 || size == 1) {
            return true;
        }
        
        ListNode* slow = head;
        ListNode* fast = head;

        //找到中间节点,并断开
        ListNode* brk = nullptr;
        while(fast && fast->next) {
            fast = fast->next->next;
            if(fast == nullptr || fast->next == nullptr) {
                brk = slow;
            }
            slow = slow->next;
        }
        brk->next = nullptr;
        
        ListNode* head1 = head;
        ListNode* head2 = reverse(slow);

        while(head1 && head2) {
            if(head1->val != head2->val) {
                return false;
            }else {
                head1 = head1->next;
                head2 = head2->next;
            }
        }
        return true;
        
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

0泡果奶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值