leetcode|Palindrome Linked List牛客網|

2564 ワード

Given a singly linked list, determine if it is a palindrome.
Follow up: Could you do it in O(n) time and O(1) space?
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null)
        return true;

<span style="white-space:pre">	</span>//     ,     ,     
    ListNode slow = head;
    ListNode fast = head.next;


    /* slow run into the middle
     * fast run into the end of list */
     while(fast!=null && fast.next!=null){
         slow = slow.next;
         fast = fast.next.next;
     }


     
     ListNode preOne = slow;
     ListNode temp = slow.next;
     ListNode aheadOne = temp;
     slow.next = null;


     /* reverse the second half pointer direction of list */
     while(temp != null){
         aheadOne = temp.next;
         temp.next = preOne;
         preOne = temp;
         temp = aheadOne;
     }


     ListNode left = head;
     ListNode right = preOne;
     while(left != null){
         if(left.val != right.val)
            return false;
         left = left.next;
         right = right.next;
     }


     return true;
    }
}

利用スタック
import java.util.*;
import java.util.Stack;
/*
public class ListNode {
    int val;
    ListNode next = null;


    ListNode(int val) {
        this.val = val;
    }
}*/
public class Palindrome {
    public boolean isPalindrome(ListNode pHead) {
        // write code here
        Stack<Integer> stack = new Stack<>();
        ListNode slowNode = pHead;
        ListNode fastNode = pHead;
        stack.add(slowNode.val);
        while(fastNode.next!=null&&fastNode.next.next!=null)
        {
            slowNode = slowNode.next;
            stack.add(slowNode.val);
            fastNode = fastNode.next.next;
        }
        if(fastNode.next==null)//  
        {
            stack.pop();
        }
        slowNode = slowNode.next;
        while(!stack.isEmpty())
        {
            if(stack.peek()!=slowNode.val)
                return false;
            slowNode = slowNode.next;
            stack.pop();
        }
        return true;
    }
}