解题思路:
回文分为两种情况,一种是奇数节点的链表,一种是偶数节点的链表,大致思路是先找到链表的中间节点,再让中间节点以后的节点指向反转,再定义左右指针,相向而行,判断链表是否回文,如图:
public class PalindromeList {
public boolean chkPalindrome(ListNode head) {
if(head == null){
return false;
}
if(head.next == null){
return true;
}
//找到中间节点
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
//把中间节点后面的节点指向反转
ListNode cur = slow.next;
while(cur != null){
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
//让左右指针判断是否回文
while(head != slow){
if(head.val != slow.val){
return false;
}
//判断链表偶数个节点的情况
if(head.next == slow){
return true;
}
head = head.next;
slow = slow.next;
}
return true;
}
}
✅每日一练:141. 环形链表 - 力扣(LeetCode)
解题思路:
定义快慢指针,让fast走2步,slow走1步,判断是否成环
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
return true;
}
}
return false;
}
}
✅每日一练:160. 相交链表 - 力扣(LeetCode)
解题思路:
我们要确保两个链表同时在终点相遇,可以让长的链表先走两个链表的长度差,然后让长短链表同时走,走到终点时,判断二者尾结点的指向是否指向同一个地址,如果相等,那么肯定有相交点了:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//求链表的长度,让长的的先走长度差的绝对值数
int lenA = 0 ;
int lenB = 0;
ListNode pl = headA;
ListNode ps = headB;
while(pl != null){
lenA++;
pl = pl.next;
}
while(ps != null){
lenB++;
ps = ps.next;
}
pl = headA;
ps = headB;
//链表的长度差
int len = lenA - lenB;
//确保len始终大于0,pl指向长的链表,ps指向短的链表
if(len < 0){
pl = headB;
ps = headA;
len = lenB - lenA;
}
//让长的链表先走len步
while(len-- != 0){
pl = pl.next;
}
while(pl != ps){
pl = pl.next;
ps = ps.next;
}
return ps;
}
}