zoukankan      html  css  js  c++  java
  • [算法]打印两个链表的公共部分

    题目:

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

    解答:

    因为是有序列表,所以从两个链表的头开始进行如下判断:

    • 如果head1的值小于head2,那么head1向下移动。
    • 如果head1的值大于head2,那么head2向下移动。
    • 如果二者的值相等,则打印这个值,然后head1和head2都向下移动。
    • head1和head2有任何一个移动到null,整个过程停止。

    程序:

    	public static 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.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();
    
    	}
    
    	public static void printLinkedList(Node node) {
    
    		System.out.print("Linked List: ");
    
    		while (node != null) {
    
    			System.out.print(node.value + " ");
    
    			node = node.next;
    
    		}
    
    		System.out.println();
    
    	}

  • 相关阅读:
    实现RHEL下KVM虚拟化
    SELinux安全扩展
    配置用户和组信息
    系统级计划任务
    syslog系统日志服务
    VNC远程连接,虚拟网络计算
    系统初始化
    备份与还原文件系统
    使用对象在方法间共享属性
    Python中*和**的使用
  • 原文地址:https://www.cnblogs.com/xiaomoxian/p/5249889.html
Copyright © 2011-2022 走看看