标签:style -- || nbsp array rom ack boolean back
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
1 import java.util.ArrayList; 2 3 public class PalindromeLinkedList { 4 static class ListNode { 5 int val; 6 ListNode next; 7 ListNode(int x) { 8 val = x; 9 } 10 } 11 12 //方法一:遍历链表,将数据存储在集合中,然后将集合的头尾进行遍历 13 public boolean isPalindrome(ListNode head) { 14 ListNode current = head; 15 ArrayList<Integer> arr = new ArrayList<>(); 16 while(current != null) { 17 arr.add(current.val); 18 current = current.next; 19 } 20 int len = arr.size(); 21 int first = 0; 22 int last = len-1; 23 while(first<last) { 24 if(!arr.get(first).equals(arr.get(last))) { 25 return false; 26 } 27 first++; 28 last--; 29 } 30 return true; 31 } 32 33 //方法二:快慢指针查找链表的中点,将链表切断为两部分,对后一半的链表进行反转,再与前一半的链表进行比较 34 public boolean isPalindrome2(ListNode head) { 35 if(head == null || head.next == null) { 36 return true; 37 } 38 ListNode slow = head; 39 ListNode fast = head; 40 //利用快慢指针查找中间节点,一个移动1个节点,另一个移动两个节点,当快指针移动到末尾时,慢指针移动到中间 41 while(fast != null && fast.next != null) { 42 slow = slow.next; //当fast为null时,节点数为偶数,slow为中间偏右 43 fast = fast.next.next; //当fast不为null时,节点数为奇数,slow为正中间 44 } 45 cutLinkedList(head, slow); 46 ListNode backHalf = reverse(slow); 47 while(head != null && backHalf != null) { 48 if(head.val != backHalf.val) { 49 return false; 50 } 51 head = head.next; 52 backHalf = backHalf.next; 53 } 54 return true; 55 } 56 public static void cutLinkedList(ListNode head, ListNode cutNode) { 57 while(head.next != cutNode) { 58 head = head.next; 59 } 60 head.next = null; 61 } 62 public static ListNode reverse(ListNode head) { 63 ListNode newHead = null; 64 while(head != null) { 65 ListNode next = head.next; 66 head.next = newHead; 67 newHead = head; 68 head = next; 69 } 70 return newHead; 71 } 72 }
标签:style -- || nbsp array rom ack boolean back
原文地址:https://www.cnblogs.com/xiyangchen/p/11057810.html