方式1:借助栈 空间辅助度是O(N)
方式2: 借助栈 空间复杂度是 O(n/2)。只存后半个链表
方式3: 反转后半个链表 最后再反转回来
1 package my_basic.class_3; 2 3 import java.util.Stack; 4 5 //是否是回文结构 121 1221, 6 public class Code_11_IsPalindromeList { 7 public static class Node{ 8 int value; 9 Node next; 10 public Node(int value) { 11 super(); 12 this.value = value; 13 } 14 } 15 16 //need extra(n) space 栈辅助 17 public static boolean isPalindrome1(Node head) { 18 Stack<Node> stack = new Stack<Node>(); 19 Node cur = head; 20 while(cur != null) { 21 stack.push(cur); 22 cur = cur.next; 23 } 24 while (head != null && !stack.empty()) { 25 if (head.value != stack.pop().value) { 26 return false; 27 } 28 head = head.next; 29 } 30 if (head==null) { 31 System.out.println("head null"); 32 } 33 return true; 34 } 35 36 //need n/2 extra space 栈辅助 37 public static Boolean isPalindrome2(Node head) { 38 Stack<Node> stack = new Stack<Node>(); 39 if (head == null || head.next == null) { 40 return true; 41 } 42 Node right = head.next; 43 Node cur = head; 44 if (cur.next!=null || cur.next.next !=null) { 45 cur = cur.next.next; 46 right = right.next; 47 } 48 while (right != null) { 49 stack.push(right); 50 right = right.next; 51 } 52 while(!stack.empty()) { 53 if (head.value != stack.pop().value) { 54 return false; 55 } 56 head = head.next; 57 } 58 return true; 59 } 60 61 //need O(1) extra space 反转半个链表 62 public static Boolean isPalindrome3(Node head) { 63 if (head == null || head.next == null) { 64 return true; 65 } 66 Node n1 = head; 67 Node n2 = head; 68 while (n2.next != null && n2.next.next!=null) { 69 n1 = n1.next; //mid 70 n2 = n2.next.next; //last 71 } 72 n2 = n1.next; //右边第一个节点 73 n1.next = null; 74 Node n3 = null; 75 while (n2 != null) { /*反转右半部分*/ 76 n3 = n2.next; 77 n2.next = n1; 78 n1 = n2; 79 n2 = n3; 80 } 81 n3 = n1; //n3->last node 82 n2 = head; 83 boolean res = true; 84 while (n2 != null && n1 != null) { 85 if (n2.value != n1.value) { 86 // return false; 不能return 还要把链表反转回来 87 res = false; 88 break; 89 } 90 n2 = n2.next; 91 n1 = n1.next; 92 } 93 94 n1 = n3.next; 95 n3.next = null; 96 while (n1 != null) { // recover list 97 n2 = n1.next; 98 n1.next = n3; 99 n3 = n1; 100 n1 = n2; 101 } 102 return res; 103 104 } 105 106 107 public static void printLinkedList(Node node) { 108 System.out.print("Linked List: "); 109 while (node != null) { 110 System.out.print(node.value + " "); 111 node = node.next; 112 } 113 System.out.println(); 114 } 115 116 117 public static void main(String[] args) { 118 Node head = null; 119 head = new Node(1); 120 head.next = new Node(2); 121 head.next.next = new Node(2); 122 head.next.next.next = new Node(2); 123 // head.next.next.next.next = new Node(1); 124 printLinkedList(head); 125 System.out.print(isPalindrome1(head) + " | "); 126 System.out.print(isPalindrome2(head) + " | "); 127 System.out.print(isPalindrome3(head) + " | "); 128 printLinkedList(head); 129 System.out.println("========================="); 130 131 } 132 }