LinkedList——No.234 Palindrome Linked List

Problem:

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

Explanation:

判断链表是否回文。

My Thinking:

使用快慢指针找到链表中点,将慢指针的结点存入栈,注意需要判断奇数还是偶数,随后慢指针继续移动,并与栈中元素判断相等。

My Solution:

class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode fast=head,slow=head;
        Stack<ListNode> nodestack=new Stack<>();
        if(head==null || head.next==null)
            return true;
        nodestack.push(slow);
        while(fast!=null && fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
            if(fast!=null)//如果是奇数
                nodestack.push(slow);
        }
        while(slow!=null){
            if(nodestack.pop().val!=slow.val)
                return false;
            slow=slow.next;
        }
        return true;
    }
}

Optimum Thinking:

不使用栈,找到中点后,对后半部分进行逆转。

Optimum Solution:

public boolean isPalindrome(ListNode head) {
    ListNode fast = head, slow = head;
    while (fast != null && fast.next != null) {
        fast = fast.next.next;
        slow = slow.next;
    }
    if (fast != null) { // odd nodes: let right half smaller
        slow = slow.next;
    }
    slow = reverse(slow);
    fast = head;
    
    while (slow != null) {
        if (fast.val != slow.val) {
            return false;
        }
        fast = fast.next;
        slow = slow.next;
    }
    return true;
}

public ListNode reverse(ListNode head) {
    ListNode prev = null;
    while (head != null) {
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }
    return prev;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值