1. 程式人生 > >算法總結之 打印兩個有序鏈表的公共部分

算法總結之 打印兩個有序鏈表的公共部分

同時 cnblogs else ack style pan his pre pri

給定兩個有序鏈表的頭指針 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(); } }

算法總結之 打印兩個有序鏈表的公共部分