代码改变世界

回文链表

2018-11-07 09:58  YihangZhou  阅读(133)  评论(0编辑  收藏  举报

 

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

 

思路:

  • 由于题目说了时间复杂度是O(n),空间复杂度是O(1),所以不能使用新的空间;
  • 思路还是反转链表,不过不是反转整个链表,反转的是后半部分的链表;

  • 后半部分的链表反转完毕,然后一个从头开始遍历,一个从尾巴开始遍历,依次比较节点的值是不是一样,一样就继续往下,不一样直接就返回false.

/**
  * Definition for singly-linked list.
  * public class ListNode {
  *     int val;
  *     ListNode next;
  *     ListNode(int x) { val = x; }
  * }
  */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null)        
            return true;
        int length = 0;
        ListNode temp = head;
        while(temp != null)
        {           
            length++;
            temp = temp.next;
        }
        int halfLength = length / 2;
        temp = head;
        for(int i=0;i<halfLength;i++)
            temp = temp.next;       
        ListNode pre = temp;
        ListNode pNode = temp.next;
        ListNode next = pNode;
        while(pNode != null)
        {            next = pNode.next;
            pNode.next = pre;
            pre = pNode;
            pNode = next;
        }
        for(int i=0;i<halfLength;i++)
        {
            if(head.val != pre.val)
                return false;
            head = head.next;
            pre = pre.next;
        }
        return true;
    }
}