打印有序链表的相同部分
首先是有序链表,所以从两个链表的头开始遍历进行判断:
- 如果head1的值<head2的,则移动head1;
- 如果head1的值>head2的,则移动head2;
- 如果head1的值=head2的,则打印这个值,然后head1和head2同时往下移动;
具体代码
public class Node {
public int value;
public Node next;
public Node(int data){
this.value = data;
}
public static void printCommonPart(Node head1,Node head2){
System.out.println("common part:" );
while(head1!=null && head2 !=null){
if(head1.value < head2.value){
head1 = head1.next;
}else if(head1.value > head2.value){
head2 = head2.next;
}else{
System.out.print( head1.value+" ");
head2 = head2.next;
head1 = head1.next;
}
}
}
public static void main(String[] args) {
Node head1 = new Node(1);
head1.next = new Node(3);
head1.next.next = new Node(5);
head1.next.next.next = new Node(6);
Node head2 = new Node(1);
head2.next = new Node(4);
head2.next.next = new Node(5);
head2.next.next.next = new Node(6);
printCommonPart(head1,head2);
}
}
输出结果




被折叠的 条评论
为什么被折叠?



