leetcode234-回文链表中文链接: https://leetcode-cn.com/problems/palindrome-linked-list/ 英文链表: https://leetcode.com/problems/palindrome-linked-list/ 难度:easy 分类:链表
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false 示例 2:
输入: 1->2->2->1 输出: true
距离AC只差一个测试用例的错误思路
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
int sum1 = 0;
if(head == null || head.next == null)
return true;
int count = 1;
ListNode temp = head;
while(temp != null)
{
sum1 += count * temp.val;
count += 1;
temp = temp.next;
}
int sum2 = 0;
count = 1;
head = reverseList(head);
temp = head;
while(temp != null)
{
sum2 += count * temp.val;
count += 1;
temp = temp.next;
}
if(sum1 == sum2)
return true;
return false;
}
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode pre = head;
ListNode pNode = head.next;
ListNode next = head;
//首先处理前两个节点;
pre.next = null;
while(pNode != null)
{
next = pNode.next;
pNode.next = pre;
pre = pNode;
pNode = next;
}
return pre;
}
}
结果,差一个用例没过,说明这种方法还是有点问题~~~~
正确的思路
代码
/**
* 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;
}
}
代码讲解