链表

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

实现:有序链表

  1. if(head1 < head2) head1移到下一个节点
  2. if(head1 > head2) head2移到下一个节点
  3. if(head1 == head2) 打印这个值,head1和head2移到下一个节点
  4. if(head 1 || head2 == null) 整个过程停止。

方法一:不用现成的链表结构,传入Node类型参数

1
2
3
4
5
6
7
8
//Node
public class Node {
public int data; //若设为private另一个类无法访问
public Node next;
public Node(int data) {
this.data = data;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//主类
public class PrintCommonPart {
public static void printCommonPart(Node head1, Node head2) {
while (head1 != null && head2 != null) {
if (head1.data < head2.data) {
head1 = head1.next;
} else if (head1.data > head2.data) {
head2 = head2.next;
} else { //head1.data == head2.data
System.out.println("相同的数据:" + head1.data);
head1 = head1.next;
head2 = head2.next;
}
}
}
//Test
public static void main(String[] args) {
Node head1 = new Node(1); //注意链表中个各结点的指向
Node node1 = new Node(2);
Node node2 = new Node(3);
Node node3 = new Node(4);
head1.next = node1;
node1.next = node2;
node2.next = node3;
Node head2 = new Node(3);
Node node4 = new Node(3);
Node node5 = new Node(3);
Node node6 = new Node(4);
head2.next = node4;
node4.next = node5;
node5.next = node6;
printCommonPart(head1, head2);
}
}