题目描述:
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解题思路:
第一步:
第二步:
代码实现(Java语言):
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode slow = head,fast = head;
while(fast != null){
slow = slow.next;
if(fast.next == null){
break;
}
fast = fast.next.next;
}
slow = reverseList(slow);
while(slow != null){
if(slow.val != head.val){
return false;
}
slow = slow.next;
head = head.next;
}
return true;
}
public ListNode reverseList(ListNode head) {
if(head==null || head.next == null)
return head;
ListNode nextNode = head.next;
ListNode cur = head;
head.next = null;
ListNode tempNext = null;
while(nextNode != null){
tempNext = nextNode.next;
nextNode.next = cur;
cur = nextNode;
nextNode = tempNext;
}
return cur;
}
}