[算法]打印两个链表的公共部分
2016-03-07 11:29
239 查看
题目:
给定两个有序链表的头指针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();
}
相关文章推荐
- 获得android应用的版本号
- sql批量替换字段里的字符串
- C++中的RTTI机制详解
- MySQL存储引擎对比
- could not resolve placeholder ${}
- C++ union enum 探究
- OkHttp的深入研究:Jesse Wilson(二)
- android contentprovider limit限定
- hiho 1271 舰队游戏 状压dp 贪心 模拟
- iOS 自定义emoji表情键盘
- Android Studio配置SVN服务器
- 一个不错的android学习网站
- 【c语言】推断一个数是不是2的n次方
- JDBC之java数据库的连接与简单的sql语句执行
- 滴滴出行高效开发保障源动力解析
- mac mysql忘记root密码
- mysql 设置初始密码、允许远程访问及忘记root密码后重设
- iOS 定位服务编程详解
- 深入使用Spring(一)
- php 学习笔记 -- 日期(四)