1. 程式人生 > >查詢兩個有序連結串列的相同部分

查詢兩個有序連結串列的相同部分

/**
 * Created by 糖糖 on 2017/8/2.
 */
public class printCommonPart {
    public static void printCommonPart(node head1,node head2){
        while (head1!= null && head2!= null){
            if(head1.data>head2.data)
                head2 = head2.next;
            else if(head1.data<head2.data
) head1 = head1.next; else { System.out.print(head1.data+" "); head1 = head1.next; head2 = head2.next; } } } public static void main(String args[]){ node n1=new node(2); node n2=new
node(5); node n3=new node(6); node n4=new node(7); n1.next=n2; n2.next=n3; n3.next=n4; node n5=new node(5); node n6=new node(6); node n7=new node(7); n5.next=n6; n6.next=n7; printCommonPart(n1,n5); } } class
node{ public int data; public node next; public node(int data){ this.data = data; } }