python mergeTwoList 合并两个有序表
要求: 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 分析: 1、分析表1和表2,创建一个新表。如果表1不存在,返回表2;如果表2不存在,返回表1; 2、对三个表,做三个指针;对比表1和表2,找到第一个数,赋值给新表第三个指针cur,同时移动其他表的指针; 3、当其中一个表结束,直接在新表中加上剩下的另外一个表即可。 4、其中最后打印112344的时候,最后一个打印不出来,需要单独打印一次。(while循环中普遍存在这个问题,一般都是先把第一个打印出来。其他循环打印) 代码: class Node:#创建链表 def __init__(self, dataval=None,nextval=None): self.dataval = dataval self.nextval = nextval class SLinkedList: def __init__(self):#创建链表 self.headval = None def mergelist(self,list1,list2): if not list2: return list1 if not list1: return list2 curNode1 = list1 curNode2 = list2 if curNode1.dataval < curNode2.dataval: head = curNode1 curNode1 = curNode1.nextval else: head = curNode2 curNode2 = curNode2.nextval cur = head while curNode1 and curNode2: if curNode1.dataval < curNode2.dataval: cur.nextval = curNode1 curNode1 = curNode1.nextval else: cur.nextval = curNode2 curNode2 = curNode2.nextval cur = cur.nextval if not curNode1: cur.nextval=curNode2 if not curNode2: cur.nextval= curNode1 return head print("................") list1 = Node("1") #list1.headval = Node("1") e2 = Node("2") e3 = Node("4") list1.nextval = e2 e2.nextval = e3 list2 = Node("1") #list2.headval = Node("1") e2 = Node("3") e3 = Node("4") list2.nextval = e2 e2.nextval = e3 s=SLinkedList() list = s.mergelist(list1,list2) while list.nextval != None: print(list.dataval) list = list.nextval print(list.dataval) 运行结果:
................ 1
1 2 3 4 4
Process finished with exit code 0