leetcode - 234 回文链表
作者:互联网
给你一个单链表的头节点 head
,请你判断该链表是否为回文链表。如果是,返回 true
;否则,返回 false
。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } if(head == null || head.next == null) { return true; } ListNode slow = head, fast = head; ListNode pre = head, prepre = null; while(fast != null && fast.next != null) { pre = slow; slow = slow.next; fast = fast.next.next; pre.next = prepre; prepre = pre; } if(fast != null) { slow = slow.next; } while(pre != null && slow != null) { if(pre.val != slow.val) { return false; } pre = pre.next; slow = slow.next; } return true; */ class Solution { public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) { return true; } ListNode slow = head; ListNode fast = head; ListNode pre = head; ListNode prepre = null; while (fast != null && fast.next!= null) { pre = slow; slow = slow.next; fast = fast.next.next; // 将前一半的链表拆开,然后逆序重组 pre.next = prepre; prepre = pre; } if (fast != null) { slow = slow.next; } while (pre != null && slow != null) { if (pre.val != slow.val) { return false; } pre = pre.next; slow = slow.next; } return true; } }
标签:pre,slow,ListNode,fast,next,链表,234,null,leetcode 来源: https://www.cnblogs.com/slidecode/p/16309299.html