判断一个链表是否为回文链表,说出你的思路并手写代码
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ if head is None or head.next is None: return True Len = 0 p = head while p: p = p.next Len += 1 prev = head now = head.next prev.next = None for i in range(Len//2-1): tmp = now.next now.next = prev prev = now now = tmp p1 = prev p2 = now if Len%2==1: p2 = p2.next while p1 is not None and p2 is not None: if p1.val != p2.val: return False p1 = p1.next p2 = p2.next if p1 is not None or p2 is not None: return False return True
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL) return true;
ListNode* slow = head,*fast = head,*p;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}
//reverse
ListNode* pre = NULL,*cur = head,*next = head;
while(cur != slow){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
slow = fast == NULL ? slow : slow->next;
while(slow && pre){
if(slow->val != pre->val) return false;
slow = slow->next;
pre = pre->next;
}
return true;
}
}; public class PalindromeList{ //找到中间节点
public ListNode getMid(ListNode head){ ListNode fast=head; ListNode slow=head; while(fast!=null){ fast=fast.next; if(fast==null){ break; } slow=slow.next; fast=fast.next; } return slow;
} //逆置从中间节点之后的链表
public ListNode reverse(ListNode head){ ListNode result=null; ListNode cur=head; while(cur!=null){ ListNode next=cur.next; cur.next=result; result=cur; cur=next; } return result;
} //然后判断相等
public boolean checkPalindromeList(ListNode head){ ListNode mid=getMid(head); ListNode node=reverse(mid); ListNode p1=head; ListNode p2=node; while(p2!=null&&p1!=null){ if(p1.val!=p2,val){ return false; } p1=p1.next; p2=p2.next; } return true;
}
}