public class Node {
public String value;
public Node next;
public Node(String value, Node next) {
this.value = value;
this.next = next;
}
}
public class LinkListTest {
public static void main(String[] args) {
Node node5 = new Node("5", null);
Node node4 = new Node("4", node5);
Node node3 = new Node("3", node4);
Node node2 = new Node("2", node3);
Node node1 = new Node("1", node2);
Node node0 = new Node("0", node1);
Node node10 = new Node("5", null);
Node node9 = new Node("4", node10);
Node node8 = new Node("3", node9);
Node node7 = new Node("2", node8);
Node node6 = new Node("0", node7);
String result = judgeLinkListTailEqual(node0, node6);
System.out.println(result);
}
public static String judgeLinkListTailEqual(Node p, Node q) {
Stack<String> pStack = new Stack<>();
Stack<String> qStack = new Stack<>();
//将链表1的节点依次放入栈中
Node pHead = p;
while (pHead != null) {
pStack.push(pHead.value);
pHead = pHead.next;
}
//将链表2的节点也依次放入栈中
Node qHead = q;
while (qHead != null) {
qStack.push(qHead.value);
qHead = qHead.next;
}
//从两个栈中一次取出一个节点进行比较,直到不相等,这是相等的最后一个值就是合并的元素
String equalNode = null;
while (!pStack.isEmpty() && !qStack.isEmpty()) {
String pValue = pStack.pop();
String qValue = qStack.pop();
if (pValue.equals(qValue)) {
equalNode = pValue;
} else {
break;
}
}
return equalNode;
}
}
评论