【Leetcode】Panlidrome Linked List

来源:互联网 发布:python 执行perl脚本 编辑:程序博客网 时间:2024/06/06 10:05

【题目】

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?


【思路】

panlidrome的话,回文,就是前后是一样的。第一个和最后一个一样, 第二个和倒数第二个一样。

linked list的话,首先要明确不能回退。如果我使用two pointers的话,一个指针再头,一个指针在最后是不可行。。


思路一: 使用stack

遍历两 遍linkedlist. 第一遍,将所有元素放入到Stack中。

第二遍遍历,就是将栈内的元素弹出来然后进行对比。

time: O(n);

space: O(n)


但是!!题目有加要求O(1)!!怎么办呢


【代码】


/** * 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)     {        Stack<Integer> s = new Stack<Integer>();        ListNode temp = head;        ListNode cur = head;        while(temp != null)        {            s.push(temp.val);            temp = temp.next;        }        while(cur != null)        {            if(cur.val != s.peek())                return false;            else            {                cur = cur.next;                s.pop();            }        }        return true;    }}


space: O(1)并没有特别好想的方法。。。

public class Solution {    public boolean isPalindrome(ListNode head) {        if(head == null) {            return true;        }        ListNode p1 = head;        ListNode p2 = head;        ListNode p3 = p1.next;        ListNode pre = p1;        //find mid pointer, and reverse head half part        while(p2.next != null && p2.next.next != null) {            p2 = p2.next.next;            pre = p1;            p1 = p3;            p3 = p3.next;            p1.next = pre;        }        //odd number of elements, need left move p1 one step        if(p2.next == null) {            p1 = p1.next;        }        else {   //even number of elements, do nothing        }        //compare from mid to head/tail        while(p3 != null) {            if(p1.val != p3.val) {                return false;            }            p1 = p1.next;            p3 = p3.next;        }        return true;    }}



0 0
原创粉丝点击