leetcode | Palindrome Linked List 牛客网 |

来源:互联网 发布:济溪环境交流网络 编辑:程序博客网 时间:2024/06/11 18:55

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;    }}


0 0
原创粉丝点击