标签:
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?
思路:
先选择中间的节点+反转链表
我的代码:
public class Solution { public boolean isPalindrome(ListNode head) { if(head == null) return true; ListNode mid = getMiddle(head); ListNode reverse = getReverse(mid); while(head!=null && reverse!=null) { if(head.val == reverse.val) { head = head.next; reverse = reverse.next; } else return false; } return true; } public ListNode getMiddle(ListNode head) { ListNode slow = head; ListNode fast = head.next; while(fast!=null && fast.next!=null) { fast = fast.next.next; slow = slow.next; } return slow; } public ListNode getReverse(ListNode head) { ListNode dummy = new ListNode(-1); while(head != null) { ListNode next = head.next; head.next = dummy.next; dummy.next = head; head = next; } return dummy.next; } }
反思:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4658404.html