当前位置: 移动技术网 > IT编程>脚本编程>Python > Python实现合并两个有序链表的方法示例

Python实现合并两个有序链表的方法示例

2019年05月29日  | 移动技术网IT编程  | 我要评论

小年夜,家长会上爸爸猝死!年仅33岁,9877mm

本文实例讲述了python实现合并两个有序链表的方法。分享给大家供大家参考,具体如下:

思路:先选出第一个节点,然后遍历两个链表,把小的作为当前节点的下一个节点,一直到其中一个链表遍历完,这时候把另一个链表直接接上就好

# definition for singly-linked list.
# class listnode(object):
#   def __init__(self, x):
#     self.val = x
#     self.next = none
class solution(object):
  def mergetwolists(self, l1, l2):
    """
    :type l1: listnode
    :type l2: listnode
    :rtype: listnode
    """
    #先考虑链表其中一个为空的情况
    if not l1:
      return l2
    if not l2:
      return l1
    curnode1 = l1
    curnode2 = l2
    #先选出第一个节点
    if curnode1.val < curnode2.val:
      head = curnode1
      curnode1 = curnode1.next
    else:
      head = curnode2
      curnode2 = curnode2.next
    cur = head
    while curnode1 and curnode2:
      if curnode1.val < curnode2.val:
        cur.next = curnode1
        curnode1 = curnode1.next
      else:
        cur.next = curnode2
        curnode2 = curnode2.next
      cur = cur.next
    #一直循环到有一个链表先结束
    #如果是链表1先结束,则拼上链表2剩余的那段
    if not curnode1:
      cur.next = curnode2
    #如果是链表2先结束,则拼上链表1剩余的那段
    else:
      cur.next = curnode1
    return head

更多关于python相关内容感兴趣的读者可查看本站专题:《python数据结构与算法教程》、《python加密解密算法与技巧总结》、《python编码操作技巧总结》、《python函数使用技巧总结》、《python字符串操作技巧汇总》及《python入门与进阶经典教程

希望本文所述对大家python程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网