题目:
请判断一个链表是否为回文链表。
示例:
代码:
- 解法一
/**
* 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;
}
ListNode mid=middleNode(head);
ListNode root=reversal(mid);
ListNode p1=head;
ListNode p2=root;
while(p2!=null&&p1.val==p2.val){
p1=p1.next;
p2=p2.next;
}
return p2==null?true:false;
}
private ListNode middleNode(ListNode head){ //寻找中心元素
ListNode slow=head;
ListNode fast=head.next;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
return slow.next;
}
//迭代实现
private ListNode reversal(ListNode head){
ListNode root=new ListNode(0);
ListNode cur=root;
while(head!=null){
cur=head;
head=head.next;
cur.next=null;
cur.next=root.next;
root.next=cur;
}
return root.next;
}
}
- 解法二
/**
* 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;
}
ListNode mid=middleNode(head);
ListNode root=reversal(mid);
ListNode p1=head;
ListNode p2=root;
while(p2!=null&&p1.val==p2.val){
p1=p1.next;
p2=p2.next;
}
return p2==null?true:false;
}
private ListNode middleNode(ListNode head){
ListNode slow=head;
ListNode fast=head.next;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
return slow.next;
}
//迭代实现
private ListNode reversal(ListNode head){
if(head==null||head.next==null){
return head;
}
ListNode h=reversal(head.next);
head.next.next=head;
head.next=null;
return h;
}
}
- 别人的代码
/**
* 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;
}
if(head.next.next==null){
return head.val == head.next.val;
}
ListNode slow = head;
ListNode fast = head.next;
while(fast.next!=null){
if(slow.val == fast.next.val){
if(fast.next.next!=null){
return false;
}
fast.next = null;
slow = slow.next;
fast = slow.next;
if(fast==null || slow.val == fast.val){
return true;
}
}else{
fast = fast.next;
}
}
return false;
}
}