打印两个有序链表的公共部分。
题目
给定两个有序链表的头指针head1和head2,打印两个链表的公共部分。
解答
核心思路
因为两个链表是有序的,所以把两个链表的节点挨个比对,如果比另外一个节点的值小,这个节点就跳到下一个节点,再进行比对,如果相同的话就输出。当其中一条链表遍历完成的时候就结束。
完整带测试代码
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| public class Solution { 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(); }
public static void main(String[] args) { Node node1 = new Node(2); node1.next = new Node(3); node1.next.next = new Node(5); node1.next.next.next = new Node(6);
Node node2 = new Node(1); node2.next = new Node(2); node2.next.next = new Node(5); node2.next.next.next = new Node(7); node2.next.next.next.next = new Node(8);
printLinkedList(node1); printLinkedList(node2); printCommonPart(node1, node2); } }
|