//主类
public class PrintCommonPart {
public static void printCommonPart(Node head1, Node head2) {
while (head1 != null && head2 != null) {
if (head1.data < head2.data) {
head1 = head1.next;
} else if (head1.data > head2.data) {
head2 = head2.next;
} else { //head1.data == head2.data
System.out.println("相同的数据:" + head1.data);
head1 = head1.next;
head2 = head2.next;
}
}
}
//Test
public static void main(String[] args) {
Node head1 = new Node(1); //注意链表中个各结点的指向
Node node1 = new Node(2);
Node node2 = new Node(3);
Node node3 = new Node(4);
head1.next = node1;
node1.next = node2;
node2.next = node3;
Node head2 = new Node(3);
Node node4 = new Node(3);
Node node5 = new Node(3);
Node node6 = new Node(4);
head2.next = node4;
node4.next = node5;
node5.next = node6;
printCommonPart(head1, head2);
}
}
近期评论