LeetCode 234. 回文链表

欢迎关注我的 力扣github仓库,有JavaScript和C++两个版本,每日更新

写在前面: 这题好无语,dev跑的结果和oj平台不一样,害我调试那么久
我是通过快慢指针+后半段反转的方式解决的,也可以快慢指针+前半段反转或者快慢指针+栈 等等方式
C++:

/**
 * 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) {
        if(!head || !head->next)
            return true;
        ListNode *fast=head,*slow=head;
		while(fast && fast->next) //利用快慢指针找到中间值
        {
            slow=slow->next;
            fast=fast->next->next;
        }

        ListNode *L=new ListNode;   //新建一个链表存放后半部分反转的值
		ListNode *temp;    //用于存放slow的下一个指向,因为头插法会使其丢失
        while(slow)
        {
            temp=slow->next;
            slow->next=L;
            L=slow;
            slow=temp;
        }
        
        while(L && L->next )
        {
            if(head->val!=L->val)
                return false;
            head=head->next;
            L=L->next;
        }
        return true;
    }
};

JS:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function(head) {
    var fast=head,slow=head;
    if(!head || !head.next)
        return true;
    while(fast && fast.next){
        slow=slow.next;
        fast=fast.next.next;
    }

    var L=new ListNode,temp;//新建一个链表存放后半部分反转的值
    while(slow){
        
        temp=slow.next;
        slow.next=L;
        L=slow;
        slow=temp;
    }

    while(L && L.next){
        if(head.val!=L.val)
            return false;        
        head=head.next;
        L=L.next;
    }
    return true;
};

234. 回文链表
请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值