Palindrome of linked list
The palindrome structure of the linked list—Niuke.com link
Topic content: 对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。 给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
Input and output example:
输入:
1->2->2->1
输出:
true
1. Code implementation
Method 1: First reverse the linked list, and then traverse and compare whether they are equal;
Reverse linked list blog, if you are interested, you can check it out
public boolean chkPalindrome(ListNode A) {
// write code here
//1.思路一:首先将链表反转,然后比较是否相等
ListNode B = reverseList(A);//将链表进行反转
//开始遍历,比较俩个链表
while (A != null){
//循环条件也可以是B不等于null,因为反转过,链表长度肯定一样
if (A.val != B.val){
return false;
}else {
A = A.next;
B = B.next;
}
}
return true;
}
//反转链表的方法
public ListNode reverseList(ListNode head) {
//迭代的方法需要保存前一个节点
ListNode pre = null;
ListNode cur = head;//用来遍历的节点
while (cur != null){
//1.首先将cur后面的链表保存下来
ListNode next = cur.next;
//2.然后将cur.next变为它的前一个节点
cur.next = pre;
//3.然后pre保存新链表(也就是反转链表的头节点)
pre = cur;
//4.cur继续遍历原来的链表
cur = next;
}
//5.遍历完成,返回新链表的头节点
return pre;
}
Method 2: The first traversal puts the value of the node into the stack, and then compares it with the elements in the stack after traversing once (using the first-in-last-out of the stack)
public boolean chkPalindrome(ListNode A) {
// write code here
Stack<Integer> stack = new Stack<>();
//1.第一遍遍历,入栈
ListNode cur = A;
while (cur != null){
stack.push(cur.val);
cur = cur.next;
}
//2.第二遍遍历,进行比较
while (A != null){
if (A.val != stack.pop()){
return false;
}
A = A.next;
}
return true;
}