From 29dbe2ddef230239be4df1b6a4773707f7147493 Mon Sep 17 00:00:00 2001 From: liuguang1 Date: Sat, 8 Dec 2018 15:52:36 +0800 Subject: [PATCH] task2 --- .../21MergeTwoOrderedLists.py" | 98 +++++++++++++++++++ ...11\345\272\217\351\223\276\350\241\250.md" | 20 ++++ 2 files changed, 118 insertions(+) create mode 100644 "\345\210\230\345\271\277\346\234\210/21MergeTwoOrderedLists.py" create mode 100644 "\345\210\230\345\271\277\346\234\210/\351\242\230\347\233\256\357\274\232\345\220\210\345\271\266\344\270\244\344\270\252\346\234\211\345\272\217\351\223\276\350\241\250.md" diff --git "a/\345\210\230\345\271\277\346\234\210/21MergeTwoOrderedLists.py" "b/\345\210\230\345\271\277\346\234\210/21MergeTwoOrderedLists.py" new file mode 100644 index 0000000..b8f4d26 --- /dev/null +++ "b/\345\210\230\345\271\277\346\234\210/21MergeTwoOrderedLists.py" @@ -0,0 +1,98 @@ +#!/user/bin/env python +#-*- coding:utf-8 -*- +# @Time : 2018/12/6 21:18 +# @Author : 刘 +# @Site : +# @File : 21MergeTwoOrderedLists.py +# @Software: PyCharm + + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +# Definition for singly-linked list. +import json +class ListNode: + def __init__(self, x): + self.val = x + self.next = None +import json +class Solution: + def mergeTwoLists(self, l1, l2): + """ + :type l1: ListNode + :type l2: ListNode + :rtype: ListNode + """ + if l1 == None and l2 == None: + return None + if l1 ==None: + return None + if l2== None: + return None + if l1.val 2->4, 1->3->4 +输出:1->1->2->3->4->4 +``` + +# 思想: + +1.确定是否两个链表是否含都为空链表 + +2.在两个链表无空链表下确定第一个节点,比较链表1与链表2的第一个节点的值,将值小的节点保存下来为合并后的第一个节点。并且把第一个节点为最小的链表向后移动一个元素。 + +3.继续在剩下的元素中选择小的值,连接到第一个结点后面,并不断next将值小的结点连接到第一个结点后面,直到某一个链表为空。 + +4.当两个链表长度不一致时,也就是比较完成后其中一个链表为空,此时需要把另外一个链表剩下的元素都连接到第一个结点的后面。 \ No newline at end of file