打印有序单链表的公共部分


一、思路

直接用两个指针或者引用对单链表进行遍历,如果两个指针的值不相同,就让小的那个往后移就行,直到相等

二、代码实现

代码如下:

	public static void printCommonPart(Node head1, Node head2) {
    
    
		System.out.print("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 + " ");
				head1 = head1.next;
				head2 = head2.next;
			}
		}
		System.out.println();
	}


总结

单链表一般都是coding问题,所含有的算法我们会考的很少但是也有像快慢指针那样很重要的算法

おすすめ

転載: blog.csdn.net/weixin_51422230/article/details/121528051