[LeetCode]Palindrome Linked List

class Solution {
    public boolean isPalindrome(ListNode head) {
    	if(head==null||head.next==null)return true;
    	ListNode thead = head;
        ListNode mid = findMid(head);
        mid = reverse(mid);
        while(mid!=null&&thead!=null){
        	if(mid.val!=thead.val){
        		return false;
        	}
        	mid = mid.next;
        	thead = thead.next;
        }
        return true;
    }
    
    public ListNode findMid(ListNode head){
    	int i = 1;
    	ListNode temp = head;
    	while(temp.next!=null){
    		temp = temp.next;
    		i++;
    	}
    	temp = head;
    	for(int j=0;j<i/2;j++){
    		temp = temp.next;
    	}
    	return temp;
    }
    
    public ListNode reverse(ListNode head){
    	if(head.next==null){
    		return head;
    	}
    	ListNode mid = head.next;
    	if(head.next.next==null){
    		head.next.next = head;
    		head.next = null;
    		return mid;
    	}else{
    		ListNode forward = head.next.next;
    		ListNode back = head;
    		head.next = null;
    		while(forward!=null){
    			mid.next = back;
    			back = mid;
    			mid = forward;
    			forward = forward.next;
    		}
    		mid.next = back;
    	}
    	return mid;
    }
}


本题的思路关键点为:


一、找到链表中点,然后断开链表,将后半部分翻转,随后进行比较。


二、对于链表操作时一定要注意对于传入的指针参数的操作,为了稳妥起见尽可能的在方法内创建一个新的指针指向传入的参数(比如head等),然后对新指针进行操作。


三、在while循环中,一定要在完成了自己需要的操作后对条件进行操作(自增,后移等)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值