(8)、链表的回文结构
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
https://www.nowcoder.com/practice/d281619e4b3e4a60a2cc66ea32855bfa?
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null || head.next==null){
return true;
}
//1、找中间节点
ListNode fast=head;
ListNode slow=head;
while(fast!=null && fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
//2、反转后半部分
ListNode cur=slow.next;
while(cur!=null){
ListNode curNext=cur.next;
cur.next=slow;
slow=cur;
cur=curNext;
}
//3、slow从后往前走,head从前往后走
while(slow != head){
if(head.val != slow.val){
return false;
}
if(head.next==slow){
return true;
}
head=head.next;
slow=slow.next;
}
return true;
}
}
(9、两个链表的第一个公共结点
https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/
public class Solution {
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode pL = headA;//永远指向长的单链表
ListNode pS = headB;//永远指向短的单链表
int lenA = 0;
int lenB = 0;
//求的lenA lenB
while (pL != null) {
lenA++;
pL = pL.next;
}
while (pS != null) {
lenB++;
pS = pS.next;
}
pL = headA;
pS = headB;
//差值-》最长的单链表先走len步
int len = lenA - lenB;
if (len < 0) {
pL = headB;
pS = headA;
len = lenB - lenA;
}
//让pL先走len步
while (len > 0) {
pL = pL.next;
len--;
}
//开始一起走 (pL != pS )---->一人一步走
while (pL != pS) {
pS = pS.next;
pL = pL.next;
}
return pL;
}
}