234. Palindrome Linked List

来源:互联网 发布:json获取key值 编辑:程序博客网 时间:2024/05/14 08:47

第一种方法,将链表中的值放到数组里,然后判断是否为回文(或者放一半进堆栈,然后判断是否为回文),然而时间复杂度为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) {        List<Integer> list = new ArrayList<Integer>();        while(head!=null){            list.add(head.val);            head = head.next;        }        for(int i=0;i<list.size()/2;i++){        //两个对象==比较的是堆中的地址,所以用equals方法比较两个Integer        //或者将Integer解包为int后用==/!=比较            if(!list.get(i).equals(list.get(list.size()-1-i))) return false;        }        return true;    }}

第二种方法,综合了链表翻转、求链表中间指针、回文比较,达到了时间复杂度为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) {       //(1)用两个指针定位链表中间的位置(第二个指针移动的速度是第一个的两倍)       //(2)将后半部分链表reverse       //(3)将前半部分链表和后半部分(reverse后)链表中放的val依次比较,判断是否为回文       if(head==null) return true;       ListNode mid = listMedium(head);       ListNode first = head;       ListNode second = listReverse(mid.next);       while(second!=null){           if(first.val!=second.val) return false;           first = first.next;           second = second.next;       }       return true;    }    private ListNode listMedium( ListNode head){        ListNode slower = head;        ListNode faster = head.next;        while(faster!=null && faster.next!=null){            slower = slower.next;            faster = faster.next.next;        }        return slower;    }    private ListNode listReverse(ListNode head){        ListNode pre = null;        ListNode cur = head;        while(cur!=null){            ListNode temp = cur.next;            cur.next = pre;            pre = cur;            cur = temp;        }        return pre;    }}
0 0
原创粉丝点击