1.设置一个回文结构,空间复杂度为o(1):
2.输入两个链表,找到第一个公共节点:
两个链表相交,是Y形状,next域相同:
先让最长的链表走两个链表的差值步数
pl:永远指向当前最长的链表
ps:永远指向当前最短的链表
public 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;
if(pl!=null){
pl=pl.next;
lenA++;
}
if(ps!=null){
ps=ps.next;
lenB++;
}
int len=lenA-lenB;
if(len<0){//说明B链表较长,将pl指向B
pl=headB;
ps=headA;
len=lenB-lenA;
}//此时能使pl永远指向最长的链表,ps永远指向最短的链表,且求出了差值
//让pl走差值len步
while (len!=0){
pl=pl.next;
len--;
}
//直到相遇
while (pl!=ps){
pl=pl.next;
ps=ps.next;
}
return pl;
}
如果没有相交的节点要捕获异常。
3.给定一个链表,判定是否有环:
定义两个指针,一个快(一次走两步),一个慢(一次走一步),只要有环,一定会相遇
public boolean hasCycle(ListNode head){
if (head==null){
return false;
}
ListNode fast=head;
ListNode slow=head;
if(fast.next!=null&&fast!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
return true;
}
}
return false;
}
创建一个环:
求环的入口点:
public ListNode detectCycle(ListNode head){
if (head==null){
return null;
}
ListNode fast=head;
ListNode slow=head;
while (fast.next!=null&&fast!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
break;//如果相遇了则有环,这里是判断有无环
}
}
if (fast==null||fast.next==null){//如果fast为空,则肯定无环
return null;
}
//上面步骤已经判断出来了有环
//当有环的时候,fast在相遇点,slow在头,一人一步,最后相遇的地方就是环的入口点
fast=head;
while (fast!=slow){
fast=fast.next;
slow=slow.next;
}
return fast;//或者return slow,这里是一样的,求出来是环的入口点
}