0
点赞
收藏
分享

微信扫一扫

如何判断两个单链表相交的第一个交点

思路分析:
首先遍历获得两个单链表得到它们的长度(长度分别记为 len1 和 len2),定义 longNode 指针指 向长度较长的单链表的首节点,定义 shortNode 指针指向长度较短的单链表的首节点,然后让 longNode 指针往后走 Math.abs(len1-len2)步。接着,定义一个循环,每次让 longNode 指针和 shortNode 指针往后移动一步,当 longNode 指针和 shortNode 指针指向同一个节点时,则停止循环。此时, longNode 和 shortNode 指向的节点,就是两个单链表相交的第一个交点。
如何判断两个单链表相交的第一个交点_数据结构

节点类

@Data
public class Node {
/**
* 用于保存节点中的数据
*/
private Object data;
/**
* 用于保存下一个节点的地址值
*/
private Node next;

public Node(Object data) {
this.data = data;
}

public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
}

实现类

package day04;

/**
* @Author yqq
* @Date 2022/05/11 12:49
* @Version 1.0
*/
public class Test08 {
public static void main(String[] args) {
//定义2个单链表
Node lastNode = new Node(77);
Node node6 = new Node(66,lastNode);
Node node3 = new Node(33,node6);
Node node2 = new Node(22,node3);
Node head1 = new Node(11,node2);
Node node5 = new Node(55,node6);
Node head2 = new Node(44,node5);
Node commonNode = getFirstCommonNode(head1, head2);
System.out.println("两个单链表相交的第一个交点:" + commonNode.getData());
}

/**
* 获得两个单链表相交的第一个交点
* @param head1 单链表1的首节点
* @param head2 单链表2的首节点
* @return
*/
public static Node getFirstCommonNode(Node head1,Node head2){
//处理head1或者head2 为null的情况
if (head1 == null || head2 ==null)
return null;
//获得以head1为首节点的单链表长度
int length1 = getLength(head1);
//获得以head2为首节点的单链表长度
int length2 = getLength(head2);
//定义longNode指针,用于指向长度较长单链表的首节点
Node longNode = length1 > length2 ? head1 : head2;
//定义shortNode指针,用于指向长度较短单链表的首节点
Node shortNode = length1 > length2 ? head2 : head1;
//让longNode指针往后移动Math.abs(length1 - length2)
for (int i = 0; i < Math.abs(length1 - length2); i++)
longNode = longNode.getNext();
//定义一个循环,每次让longNode和shortNode往后移动一次
while (longNode !=shortNode){
longNode = longNode.getNext();
shortNode = shortNode.getNext();
}
//执行到这里返回两个单链表相交的节点
return longNode;
}

/**
* 获得单链表的长度
* @param headNode 单链表的首节点
* @return 返回单链表的长度
*/
public static int getLength(Node headNode){
//定义一个变量存储单链表的长度
int length = 0;
//定义一个循环,用于实现单链表的遍历操作
Node tempNode = headNode;
while (tempNode != null){
tempNode = tempNode.getNext();
//更新length的值
length++;
}
//返回单链表的长度
return length;
}
}

如何判断两个单链表相交的第一个交点_数据结构_02


举报

相关推荐

0 条评论