判断回文链表的三种解法

1.用栈

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        stack<ListNode*>st;
        ListNode*cur1=head;
        ListNode*cur2=head;
        while(cur1){
            st.push(cur1);
            cur1=cur1->next;
        }
        while(cur2){
            ListNode*popNode=st.top();
            st.pop();
            if(popNode->val!=cur2->val) return false;
            cur2=cur2->next;
        }
        return true;

    }
};

2.用栈和快慢指针

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        stack<ListNode*>st;
        ListNode*slow=head;
        ListNode*fast=head;
        if(head==NULL) return true;
        while(fast->next!=NULL&&fast->next->next!=NULL){
            st.push(slow);
            slow=slow->next;
            fast=fast->next->next;
        }
        // 此时若整个链表为双数,slow指向上一半的最后一个,需要入栈slow
		// 若为单数,指向中间元素,不需要入栈slow
		// 单双数的判断由quick的终止条件确定
        if (fast->next!=NULL) {
			st.push(slow);
		}
        slow=slow->next;
        while(!st.empty()){
            ListNode*popNode=st.top();
            st.pop();
            if(popNode->val!=slow->val) return false;
            slow=slow->next;
        }
        return true;

    }
};

3.快慢指针和反转链表

public class Main {
	public static boolean process(Node header) {
		if (header == null) {
			return false;
		}
		Node slow = header;
		Node quick = header;
		while (quick.next != null && quick.next.next != null) {
			slow = slow.next;
			quick = quick.next.next;
		}
		slow=slow.next;
		Node preNode=null;
		Node postNode=null;
		// 后半段反转
		while (slow!=null) {
			preNode=slow.next;
			slow.next=postNode;
			postNode=slow;
			slow=preNode;
		}
		Node tailLeft=header;
		Node tailRight=postNode;
		boolean flag=true;
		// 两边向中间判断
		while (tailRight!=null) {
			if (tailLeft.value!=tailRight.value) {
				flag=false;
				break;
			}
			tailLeft=tailLeft.next;
			tailRight=tailRight.next;
		}
		Node tailNode=null;
		// 后半段链表恢复
		while (postNode!=null) {
			preNode=postNode.next;
			postNode.next=tailNode;
			tailNode=postNode;
			postNode=preNode;
		}
		return flag;
	}

	public static class Node {
		int value;
		Node next;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值