234. Palindrome Linked List

来源:互联网 发布:数据字典的定义 编辑:程序博客网 时间:2024/05/22 10:47
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?

Subscribe to see which companies asked this question

Hide Tags Linked List Two Pointers
Hide Similar Problems (E) Palindrome Number (E) Valid Palindrome (E) Reverse Linked List
分析:
思路一:可以遍历一边链表,将链表元素存在栈中,然后将元素出栈,和链表元素进行比较。第一次遍历将元素入栈,第二次遍历比较是否为回文。时间复杂度O(N),空间O(N).
思路二:使用双指针法寻找链表中间节点和末尾节点,从中间将链表拆分为两部分,后半部分翻转,然后进行比较。时间复杂度为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) {        if(head==null||head.next==null){            return true;        }        ListNode mid=partition(head);       // System.out.println(mid.val);         mid=reverse(mid);                while(head!=null&&mid!=null){            if(head.val!=mid.val){                return false;            }            head=head.next;            mid=mid.next;        }        return true;    }           public static ListNode partition(ListNode head){       ListNode p=head;       ListNode q=head;       while(q.next!=null&&q.next.next!=null){           p=p.next;           q=q.next.next;       }       q=p.next;       p.next=null;       return q;          }        public static ListNode reverse(ListNode start){        if(start==null||start.next==null){            return start;        }        ListNode pre=start;        ListNode cur=start.next;        ListNode next=null;        pre.next=null;//注意这里,一定要设置pre的下一个值为空        while(cur!=null){            next=cur.next;            cur.next=pre;            pre=cur;            cur=next;        }        return pre;    }}


0 0
原创粉丝点击