您的位置:首页 > 其它

CheckPalindrom int LinkedList

2014-02-26 02:47 423 查看
public static boolean(ListNode l1,ListNode l2){
boolean res = false;
int [] check = {-1};
ListNode mid = getMid(head,check);
if( check[0]==1){
ListNode next = mid.next;
ListNode newHead =reverse(next);
res=checkPalidrom(head, newHead  );
newHead =reverse(newHead);
mid.next = newHead;
}
else if(check[0]==0){
ListNode next = mid.next;
ListNode newHead =reverse(next);
res = checkPalidrom(head, newHead );
newHead =reverse(newHead);
mid.next = newHead;
}
return res;
}

public static ListNode reverse(ListNode head){
if(head==null || head.next==null) return head;
ListNode cur = head, post = head.next;
while(post!=null){
ListNode temp = post.next;
post.next = cur;
cur = post;
post = temp;
}
head.next = null;
return cur;
}

public static ListNode getMid (ListNode l1, int[] check){
ListNode fast = l1,slow = l1;
while(true){
fast = fast.next;
if(fast==null) {check[0]=1; return slow; };
fast = fast.next;
if(fast==null) { check[0]=0; return slow;};
slow=slow.next;
if(slow==fast) return slow;
}
}
public static boolean checkPalidrom(ListNode l1,ListNode l2 ){
while(l1!=null && l2!=null){
if(l1.val!=l2.val) return false;
l1 = l1.next;
l2 = l2.next;
}
return true;
}


View Code
1 find the mid of the list

2check the len is odd or even

3 reverse

4compare

5recover
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: