【LeetCode】—— 回文链表
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
示例 1:

输入:head = [1,2,2,1]
输出:true
示例 2:

输入:head = [1,2]
输出:false
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 public boolean isPalindrome(ListNode head) { 13 // 判断是否为空 14 if (head == null){ 15 return true; 16 } 17 // 找到前半段尾节点(奇数为中间,偶数为前半段最后一个) 18 ListNode firstHalfEnd = firstHalfEnd(head); 19 // 翻转后半段的链表 20 ListNode reverseNode = reverseList(firstHalfEnd.next); 21 // 比较两条链表 22 // 为了复原链表 23 boolean result = true; 24 ListNode p1 = head; 25 ListNode p2 = reverseNode; 26 while (result && p2!= null){ 27 if (p1.val != p2.val){ 28 result = false; 29 } 30 p1 = p1.next; 31 p2 = p2.next; 32 } 33 // 将链表复原 34 firstHalfEnd.next = reverseList(reverseNode); 35 return result; 36 } 37 // 翻转后半段的链表 38 public ListNode reverseList(ListNode head){ 39 ListNode prev = null; 40 ListNode curr = head; 41 while(curr != null){ 42 ListNode tmp = curr.next; 43 curr.next = prev; 44 prev = curr; 45 curr = tmp; 46 } 47 return prev; 48 } 49 50 // 通过快慢指针找到前半部分链表的尾节点 51 public ListNode firstHalfEnd(ListNode head){ 52 ListNode slow = head; 53 ListNode fast = head; 54 while (fast.next!=null && fast.next.next!=null){ 55 slow = slow.next; 56 fast = fast.next.next; 57 } 58 return slow; 59 } 60 }
解题关键:
1.找到前半段的尾节点
2.翻转后半段链表
3.比对前后链表

浙公网安备 33010602011771号