package com.example;
public class Main {
public static int length(LinkedNode node) {
int len = 0;
LinkedNode current = node;
while (current != null) {
len++;
current = current.getNext();
}
return len;
}
public static String check(LinkedNode l1, LinkedNode l2) {
// 长度匹配
int len1 = length(l1);
int len2 = length(l2);
LinkedNode ln;
LinkedNode sn;
if (len1 > len2) {
ln = l1;
sn = l2;
} else {
ln = l2;
sn = l1;
}
int abs = Math.abs(len1 - len2);
for (int i = 0; i < abs; i++) {
ln = ln.getNext();
}
while (ln != null) {
if(ln.getValue() == null && sn.getValue() == null) {
return "null";
}
if (ln.getValue().equals(sn.getValue())) {
return ln.getValue();
}
ln = ln.getNext();
sn = sn.getNext();
}
return null;
}
public static void main(String[] args) {
LinkedNode l1 = new LinkedNode("a");
LinkedNode l2 = new LinkedNode("d");
l1.addNode(new LinkedNode("b"));
l1.addNode(new LinkedNode("x"));
l1.addNode(new LinkedNode("y"));
l1.addNode(new LinkedNode("z"));
l1.show();
l2.addNode(new LinkedNode("e"));
l2.addNode(new LinkedNode("f"));
l2.addNode(new LinkedNode("x"));
l2.addNode(new LinkedNode("y"));
l2.addNode(new LinkedNode("z"));
l2.show();
System.out.println(check(l2, l1));
}
}
评论