leetcode234. Palindrome Linked List(类似143)

题目描述

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

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

代码

同143的处理,快慢指针将链表分为前后两条,后一条进行reverse操作后进行比对。此处reverse采用一边遍历一边改变指针的方法。

#include <iostream>

using namespace std;

/// Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

/// Two Pointers to Reverse and Traverse
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
    bool isPalindrome(ListNode* head) {

        if(head == NULL || head->next == NULL)
            return true;

        ListNode* slow = head;
        ListNode* fast = head;
        while(fast->next != NULL && fast->next->next != NULL){
            slow = slow->next;
            fast = fast->next->next;
        }

        slow->next = reverse(slow->next);

        slow = slow->next;
        ListNode* cur = head;
        while(slow != NULL){
            if(cur->val != slow->val)
                return false;
            else{
                slow = slow->next;
                cur = cur->next;
            }
        }
        return true;
    }

private:
    ListNode* reverse(ListNode* head){ //一边遍历一边改变指针

        if(head == NULL || head->next == NULL)
            return head;

        ListNode* pre = head;
        ListNode* cur = head->next;
        ListNode* next = cur->next;
        head->next = NULL;

        while(true){
            cur->next = pre;
            pre = cur;
            cur = next;
            if(cur == NULL)
                break;
            next = cur->next;
        }

        return pre;
    }
};

int main() {

    return 0;
}

思路二(浅)

(移动过程中进行前半部分链表的翻转)
思想很很简单,用2个指针,一个low,一个fast,fast是low的2倍,所以可以达到2分链表的效果
,在移动指针时同时对前半部分链表进行反转。最后直接比较被分开的2个链表
因为不能改变当前slow的next,不然就无法跳到下一个元素,所以这里用pre和prepre实现指针的反转
时间复杂度:第一个循环O(n/2),第2个循环O(n/2)

public boolean isPalindrome(ListNode head) {
    	if(head == null || head.next == null) return true;
    	ListNode slow = head, fast = head.next, pre = null, prepre = null;
    	while(fast != null && fast.next != null) {
    		//反转前半段链表
    		pre = slow;
    		slow = slow.next;
    		fast = fast.next.next;
    		//先移动指针再来反转
    		pre.next = prepre;
    		prepre = pre;
    	}
    	ListNode p2 = slow.next;
    	slow.next = pre;
    	ListNode p1 = fast == null? slow.next : slow;
    	while(p1 != null) {
    		if(p1.val != p2.val)
    			return false;
    		p1 = p1.next;
    		p2 = p2.next;
    	}
		return true;
    }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值