對於一個鏈表,請設計一個時間複雜度爲O(n),額外空間複雜度爲O(1)的算法,判斷其是否爲迴文結構。 給定一個鏈表的頭指針A,請返回一個bool值,表明其是否爲迴文結構。保證鏈表長度小於等於900。 連接java
1->2->2->1 返回:true
能夠利用數據結構中的棧來進行判斷算法
import java.util.*; /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class PalindromeList { public boolean chkPalindrome(ListNode A) { Stack<Integer> stack = new Stack<Integer>(); ListNode cur = A; while(cur != null){ if(!stack.isEmpty() && stack.peek() == cur.val){ stack.pop(); }else{ stack.push(cur.val); } cur = cur.next; } return stack.isEmpty(); } }
import org.junit.; import static org.junit.Assert.;數據結構
public PalindromeListTest { @Test public void testOne() { ListNode A = new ListNode(1); ListNode B = new ListNode(2); ListNode C = new ListNode(2); ListNode D = new ListNode(1);測試
A.next = B; B.next = C; C.next = D; assertEquals(true, new PalindromeList().chkPalindrome(A)); }
}this