1. 程式人生 > >回文鏈表

回文鏈表

true efi 比較 ron nbsp bool next strong 空間

請判斷一個鏈表是否為回文鏈表。

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

回文鏈表