有两个已排好序的链表A和B。
A = [1, 3, 4, 6,8,10, 17, 34]
B = [2, 8, 17, 33, 44, 66, 89, 100, 123]
写程序打印这些数字:
1) 在A中但是不在B中
2) 在B中但是不在A中
You have two sorted list A and B.
A = [1, 3, 4, 6,8,10, 17, 34]
B = [2, 8, 17, 33, 44, 66, 89, 100, 123]
Write a program to print those numbers which are
1) in A and not in B
2) in B and not in A
Eg: After print: 1 , 3 , 4 , 6 , 10, 33, 34, 44,, 66, 89, 100, 123
对于每个问题,输出包含两问的输出。
方法如下:
使用各自指向A和B第一个元素的两个指针。
当两个指针都在链表范围内的时候比较两个指针指向的值。
如果相等,同时向后移动两个指针,直到所指向的元素不等于刚才相等的元素。
如果一个比另一个小,打印小的值,同时增加指向刚刚被打印值的指针。
打印未完成的链表中剩余的值。
使用O(n)时间 常数的空间。
need more clarification, as per the question, out put should contain 2 as well.
if that is the case, below will work.
take 2 pointers which points to the first elements of A and B respectively.
while both pointers are in list range compare the values pointer by the pointers
if both values are equal, increment both pointers till the next value not equal to current value.
if one less than the other, print the smaller value and increment the pointer which points to smaller one.
print the remaining values in the non completed list.
time O(n) and constant space.