請判斷一個鏈表是否為回文鏈表。
示例 1:
輸入: 1->2
輸出: false
示例 2:
輸入: 1->2->2->1 輸出: true
思路:
1.通過快慢指針,來遍歷鏈表,當快指針走到末尾時,慢指針即指向鏈表中點
2.將后半段反轉
3.將后半段與前半段進行對比,如果data相同,則繼續遍歷,直至到達末尾,return ture, 如果中間匹配不相同,return false
代碼實現:
簡單定義一個節點類型:
class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
判斷是否為回文鏈表的API
/** * 判斷鏈表是否為回文鏈表 * * @param head * @return */ public static boolean isPalindrome(ListNode head) { //如果鏈表只有一個有效節點或者沒有有效節點,return true if (head == null || head.next == null) { return true; } ListNode quick = head; ListNode slow = head; //快慢指針,快指針一次走兩步,慢指針一次走一步 while (quick != null && quick.next != null) { quick = quick.next.next; slow = slow.next; } //從slow開始反轉后半段鏈表 ListNode pre = null; ListNode p = slow; while (p != null) { ListNode temp = p.next; p.next = pre; pre = p; p = temp; } //對比前半段和后半段的data值是否相同 while (pre != null) { if (pre.val == head.val) { pre = pre.next; head = head.next; } else { return false; } } //返回true return true; }
測試:
public static void main(String[] args) { //測試 ListNode head = new ListNode(1); ListNode p2 = new ListNode(2); ListNode p3 = new ListNode(2); ListNode p4 = new ListNode(1); head.next = p2; p2.next = p3; p3.next = p4; System.out.println(isPalindrome(head)); }
結果:
true