반응형
SMALL
https://leetcode.com/problems/merge-two-sorted-lists/description/
이 문제는 풀긴 풀었다
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
ans = ListNode(0)
tmp = ans
while list1 != None and list2 != None:
if (list1.val <= list2.val):
tmp.next = ListNode()
tmp = tmp.next
tmp.val = list1.val
list1 = list1.next
else:
tmp.next = ListNode()
tmp = tmp.next
tmp.val = list2.val
list2 = list2.next
while list1:
tmp.next = ListNode()
tmp = tmp.next
tmp.val = list1.val
list1 = list1.next
while list2:
tmp.next = ListNode()
tmp = tmp.next
tmp.val = list2.val
list2 = list2.next
return ans.next
근데 https://ggodong.tistory.com/359 이 문제처럼 생각 덜 해가지고 코드가 개판이다.
리트코드는 코드의 품질도 중요하다고 하던데
또 생각안하고 풀면 뺨싸다구다
고친 후
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
ans = ListNode(0)
cur = ans
while list1 != None and list2 != None:
if (list1.val <= list2.val):
cur.next = list1
list1 = list1.next
else:
cur.next = list2
list2 = list2.next
cur = cur.next
if list1:
cur.next = list1
else:
cur.next = list2
return ans.next
반응형
LIST
'알고리즘 문제 풀이 > LeetCode' 카테고리의 다른 글
82. Remove Duplicates from Sorted List 2 (0) | 2021.11.09 |
---|---|
1038. Binary Search Tree to Greater Sum Tree (0) | 2020.07.26 |
1409. Queries on a Permutation With Key (0) | 2020.07.25 |
85. Maximal Rectangle (2) | 2020.07.08 |
84. Largest Rectangle in Histogram (0) | 2020.07.07 |