题目描述
判断一个链表是否为回文链表
分析
- 使用空间为n:将链表整个压入栈。然后栈元素弹出。挨个比较元素是否相同。
- 使用空间为n/2:快慢指针。快指针一次两步慢指针一次一步。快指针到达结尾时,慢指针到达中间,中间部分之后压入栈。然后栈弹出元素,与前半部分相比较。
- 不使用额外空间:快慢指针。快指针一次两步慢指针一次一步。快指针到达结尾时,慢指针到达中间。然后将后半部分链表逆序。两个指针分别从头尾出发,进行元素比较。最后要将后半部分再还原回来。
代码
//压栈
public static boolean isPalindrome1(Node head){
Stack<Node> stack = new Stack<>();
Node cur = head;
while(cur!=null){
stack.push(cur);
cur = cur.next;
}
cur = head;
while(cur!=null){
if(cur.value!=stack.pop().value){
return false;
}
cur = cur.next;
}
return true;
}
//快慢指针 n/2
public static boolean isPalindrome2(Node head){
if(head==null || head.next==null){
return true;
}
Node cur = head;
//因为慢指针需要走到中间靠后的一个位置
Node right =head.next;
while (cur.next!=null && cur.next.next!=null){
cur = cur.next.next;
right = right.next;
}
Stack<Node> stack = new Stack<>();
while(right!=null){
stack.push(right);
right = right.next;
}
while (!stack.isEmpty()){
if(head.value!=stack.pop().value){
return false;
}
head = head.next;
}
return true;
}
//快慢指针 后半部分反转链表 不占用额外空间
public static boolean isPalindrome3(Node head){
if(head==null || head.next==null){
return true;
}
Node n1 = head;//慢
Node n2 = head;//快
while(n2.next!=null &&n2.next.next!=null){
n1 = n1.next;
n2 = n2.next.next; //奇数到中点 偶数到两个中点的前一个
}
n2 = n1.next;
//先断后连
/*
链表逆序:
需要三个指针 后指针占后、当前指针连接、前指针后移、当前指针后移
将第一个节点的next设为空
改变所有后面指针的next
前指针后移;后指针后移
*/
n1.next = null;
Node n3 = null;
while(n2 != null){// right part convert
n3 = n2.next;// n3 -> save next node
n2.next = n1;
n1 = n2;// n1 move
n2 = n3;// n2 move
}
n3 = n1;//保存最后一个节点
n2 = head;
boolean res = true;
while(n1!=null&&n2!=null){
if(n1.value!=n2.value){
res = false;
break;//不能急着返回,需要还原列表
}
n1 = n1.next;
n2 = n2.next;
}
n1 = n3.next;
n3.next = null; //头部指针断掉
/*
1.断头部指针
2. 改变所有后面指针的next
前指针后移;后指针后移
需要三个指针
(在断掉后者重新连接的时候,一定需要一个先占住)
后指针占后、 当前指针连接、前指针后移、当前指针后移
*/
while(n1!=null){
n2 = n1.next;
n1.next = n3;
n3 = n1;
n1 = n2;
}
return res;
}
// 后半部分反转简便写法
public boolean isPalindrome4(ListNode head) {
if(head==null || head.next==null) return true;
ListNode slow = head;
ListNode fast = head;
while(fast.next!=null && fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
}
ListNode l_end = slow;
ListNode r_start = slow.next;
l_end.next = null;
ListNode r_restart = reverse(r_start);
ListNode l_start = head;
// 使用一个值保存比较的值是否相等
boolean res = true;
ListNode l_cur = l_start;
ListNode r_cur = r_restart;
while(l_cur!=null && r_cur!=null){
if(l_cur.val!=r_cur.val){
res = false;
break;
}
l_cur = l_cur.next;
r_cur = r_cur.next;
}
//将后面反转并连接
r_start = reverse(r_restart);
r_restart.next = null;
l_end.next = r_start;
return res;
}
public ListNode reverse(ListNode head){
ListNode cur = head;
ListNode pre = null;
while(cur!=null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}