算法总结之 打印两个有序链表的公共部分

给定两个有序链表的头指针 head1 和 head2,打印两个链表的公共部分

思路: 

  有序嘛,

 如果head1 的值小于 head2, head1往下移动

 如果head2的值小于head1,head2往下移动

 如果相等,打印这个值,然后同时向下移动

 两个有一个为null, 整个过程停止

package TT;

import java.time.temporal.ValueRange;

public class Test84 {

    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.println(head1.value+"");
                head1 = head1.next;
                head2 = head2.next;
            }
              
        }
        System.out.println();
       
   }


}
原文地址:https://www.cnblogs.com/toov5/p/7497856.html