按要求打印两个已排序链表中的元素

6 篇文章 0 订阅

有两个已排好序的链表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.










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值