import java.util.HashMap;
import java.util.Hashtable;
Class Node{
int value;
Node next;
}
Class CNode extends Node{
Node random;
CNode next;
public CNode(int value){
this.value=value;
this.next=null;
this.random=null;
}
}
public class Solution {
/**
* 判断链表是否带环,在这里使用快指针和慢指针,如果存在快指针等于慢指针的情况则链表带环
* @param head 传入链表头结点
* @return 返回布尔类型的值
*/
public boolean isRinged(Node head){
if(head==null){
return false;
}
Node fast=head;
Node slow=head;
while(fast.next!=null && fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
if(slow==fast){
return true;
}
}
return false;
}
/**
* 不知道头结点的情况下删除指定节点
* @param node 要删除的节点
* @return 返回布尔值,是否删除成功
*/
public static boolean deleteSpecialNode(Node node){
if(node.next==null){
return false;
}
Node next=node.next;
int tmp=node.value;
node.value=next.value;
next.value=tmp;
node.next=next.next;
return true;
}
/**
* 判断两条链表是否交叉,因为两条链表交叉最后一个节点一定一样
* @param head1 链表1
* @param head2 链表2
* @return 返回两条链表是否相交的结果
*/
public static boolean isCross(Node head1,Node head2){
if(head1==null || head2==null){
return false;
}
Node cur1=head1;
Node cur2=head2;
while(cur1.next!=null){
cur1=cur1.next;
}
while(cur2.next!=null){
cur2=cur2.next;
}
if(cur1==cur2){
return true;
}
return false;
}
/**
* 如果链表相交,寻找两条链表相交的起始节点,先判断两条链表是否相交?
* 是的话,求得两条链表的长度之差,然后再同步走,直到遇见相同的节点,返回即可
* @param head1 链表1
* @param head2 链表2
* @return 返回找见的相交的起始节点
*/
public static Node findCrossPoint(Node head1,Node head2){
if(!isCross(head1,head2)){
return null;
}
int len1=linkLens(head1);
int len2=linkLens(head2);
int len=len1-len2;
Node cur1=head1;
Node cur2=head2;
if(len>0){
for (int i = 0; i <len ; i++) {
if(cur1!=null){
cur1=cur1.next;
}
}
}
if(len<0){
len =(-1)*len;
for (int i = 0; i < len; i++) {
if(cur2!=null){
cur2=cur2.next;
}
}
}
while(cur1!=cur2){
cur1=cur1.next;
cur2=cur2.next;
}
return cur1;
}
}
Java链表面试题(3)
最新推荐文章于 2022-09-13 09:36:42 发布