打印两个有序链表的公共部分
生活随笔
收集整理的這篇文章主要介紹了
打印两个有序链表的公共部分
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【題目】 給定兩個有序鏈表的頭指針head1和head2,打印兩個 鏈表的公共部分
思路:因為是有序鏈表,所以從兩個鏈表的頭開始進行如下判斷:
如果head1的值小于head2 ,則head1 往下移動
如果head2的值小于head1?,則head2?往下移動
如果head1和head2的值相等,則打印這個值,然后head1和head2都往下移動
head1和head2有任何一個移動到null,則整個過程停止
class Node():def __init__(self,val=None):self.value = valueself.next = Nonedef printCommonpart(head1,head2):if head1 == None or head2 == None:print("common part = " + " ")while head1!=None and head2!=None:if head1.value < head2.value:head1 = head1.nextelif head1.value > head2.value:head2 = head2.nextelse:print("common part = " + head1.value)head1 = head1.nexthead2 = head2.nextprint()?
總結
以上是生活随笔為你收集整理的打印两个有序链表的公共部分的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在行列都排好序的矩阵中找数
- 下一篇: 将单向链表按某值分成左边小、中间相等、右