Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions 刘广月/21MergeTwoOrderedLists.py
Original file line number Diff line number Diff line change
@@ -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 <l2.val:
l1.next =self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = self.mergeTwoLists(l1,l2.next)
return l2


def stringToIntegerList(input):
return json.loads(input)


def stringToListNode(input):
# Generate list from the input
numbers = stringToIntegerList(input)

# Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next

ptr = dummyRoot.next
return ptr


def listNodeToString(node):
if not node:
return "[]"

result = ""
while node:
result += str(node.val) + ", "
node = node.next
return "[" + result[:-2] + "]"


def main():
import sys
import io
def readlines():
for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
yield line.strip('\n')

lines = readlines()
while True:
try:
line = next(lines)
l1 = stringToListNode(line)
line = next(lines)
l2 = stringToListNode(line)

ret = Solution().mergeTwoLists(l1, l2)

out = listNodeToString(ret)
print(out)
except StopIteration:
break


if __name__ == '__main__':
main()
20 changes: 20 additions & 0 deletions 刘广月/题目:合并两个有序链表.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# 题目:

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

**示例:**

```html
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
```

# 思想:

1.确定是否两个链表是否含都为空链表

2.在两个链表无空链表下确定第一个节点,比较链表1与链表2的第一个节点的值,将值小的节点保存下来为合并后的第一个节点。并且把第一个节点为最小的链表向后移动一个元素。

3.继续在剩下的元素中选择小的值,连接到第一个结点后面,并不断next将值小的结点连接到第一个结点后面,直到某一个链表为空。

4.当两个链表长度不一致时,也就是比较完成后其中一个链表为空,此时需要把另外一个链表剩下的元素都连接到第一个结点的后面。