LeetCode-Palindrome Linked List
Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) time and O(1) space?
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public boolean isPalindrome(ListNode head) { if(head == null){ return true; } ListNode mid=findMiddle(head); mid.next=reverse(mid.next); ListNode p1=head, p2=mid.next; while(p2 != null && p1 != null && p1.val == p2.val){ p1=p1.next; p2=p2.next; } if(p2 == null){ return true; } else{ return false; } } public ListNode findMiddle(ListNode head){ if(head ==null){ return null; } ListNode slow=head, fast=head.next; while(fast != null && fast.next !=null){ slow=slow.next; fast=fast.next.next; } return slow; } public ListNode reverse(ListNode head){ ListNode prev=null; while(head != null){ ListNode temp=head.next; head.next=prev; prev=head; head=temp; } return prev; } }
二刷, 注意findmid时候fast的起始点位和如何跳出while循环:
/** * 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){ return true; } ListNode mid = findMid(head); ListNode head2 = mid.next; mid.next = null; head2 = reverse(head2); while(head != null && head2 != null){ if(head.val != head2.val){ return false; } head = head.next; head2 = head2.next; } return true; } public ListNode findMid(ListNode head){ if(head == null){ return null; } ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; } return slow; } public ListNode reverse(ListNode head){ if(head == null){ return null; } ListNode next = head.next; head.next = null; while(next != null){ ListNode temp = next.next; next.next = head; head = next; next = temp; } return head; } }
posted on 2016-05-25 03:55 IncredibleThings 阅读(125) 评论(0) 编辑 收藏 举报