考察点
链表的遍历
知识点
题目
分析
题目要求俩个链表第一个公共结点,最简单的办法就是俩个for循环依次遍历俩个链表,这种时间复杂度会很高。针对链表的题目,我们应该好好观察链表自身的特点再决定算法,假设俩个链表长度一样,同步开始往后一次遍历俩个链表就可以很快拿到公共结点,所以我们需要解决的问题是如何让这俩个长度不一的链表变成一样的,这个就很简单了,我们分别求出俩个链表的长度并且求出diff,然后让更长的那个链表先往后遍历diff步,这样俩个链表长度就一样了。
public class ThirtySeven {
public static void main(String[] args) {
LinkList linkListOne = new LinkList();
linkListOne.addNode(1);
linkListOne.addNode(2);
linkListOne.addNode(3);
linkListOne.addNode(6);
linkListOne.addNode(7);
LinkList linkListTwo = new LinkList();
linkListTwo.addNode(4);
linkListTwo.addNode(5);
linkListOne.buildCommonList(linkListTwo,4);
//linkListOne.print();
//linkListTwo.print();
linkListOne.printCommonNode(linkListTwo);
}
}
import java.util.Deque;
import java.util.LinkedList;
public class LinkList {
LinkNode head;
public LinkList() {
this.head = null;
}
//添加元素
public void addNode(int data) {
LinkNode node = new LinkNode(data);
if (this.head == null) {
this.head = node;
} else {
LinkNode cur = this.head;
while(cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
}
//正序打印
public void print() {
LinkNode node = this.head;
while(node != null) {
System.out.print(node.val);
System.out.print(" ");
node = node.next;
}
System.out.println();
}
//构造具有公共结点的列表
public void buildCommonList(LinkList listTwo,int firstRank) {
LinkNode nodeOne = this.head;
LinkNode nodeTwo = listTwo.head;
if(nodeOne == null || nodeTwo == null) {
return;
}
int cnt = 1;
while(cnt < firstRank) {
nodeOne = nodeOne.next;
cnt++;
}
while(nodeTwo.next != null) {
nodeTwo = nodeTwo.next;
}
while(nodeOne != null) {
nodeTwo.next = nodeOne;
nodeOne = nodeOne.next;
nodeTwo = nodeTwo.next;
}
}
//获取链表长度
public int getLength(LinkNode node) {
int cnt = 0;
while(node != null) {
cnt = cnt + 1;
node = node.next;
}
return cnt;
}
public LinkNode getHead() {
return this.head;
}
//获取公共结点
public void printCommonNode(LinkList listTwo) {
LinkNode headOne = this.head;
LinkNode headTwo = listTwo.head;
if(headOne == null || headTwo == null) {
return;
}
int cntOne = getLength(headOne);
int cntTwo = getLength(headTwo);
int cnt = 0;
if(cntOne > cntTwo) {
cnt = cntOne - cntTwo;
while(cnt > 0) {
headOne = headOne.next;
cnt--;
}
} else if(cntOne < cntTwo) {
cnt = cntTwo - cntOne;
while(cnt > 0) {
headTwo = headTwo.next;
cnt--;
}
}
while(headOne != null && headTwo != null) {
if(headOne == headTwo) {
System.out.println(headOne.val);
break;
}
headOne = headOne.next;
headTwo = headTwo.next;
}
}
}
public class LinkNode {
int val;
LinkNode next;
public LinkNode(int data) {
this.val = data;
this.next = null;
}
}