@Ishishow is running a free English word site E-tan.
I would like to work on letcode every day to improve my ability as a programmer and give my own way of solving it.
leetcode.com This is the practice of coding interviews for software developers. A total of more than 1,500 coding questions have been posted, and it seems that the same questions are often asked in actual interviews.
Introduction to Go language + algorithm I will solve it with Golang and Python to strengthen my brain. (Python is weak but experienced)
--Problem content (Japanese translation)
Merges two sorted linked lists and returns them as a new ** sorted ** list. The new list must be created by joining the nodes of the first two lists together.
Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: l1 = [], l2 = []
Output: []
Example 3:
Input: l1 = [], l2 = [0]
Output: [0]
--Answer code
class Solution(object):
def mergeTwoLists(self, l1, l2):
cur = ListNode(0)
res = cur
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return res.next
--I'll write it in Go too!
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
cur := &ListNode{}
res := cur
for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
cur.Next = l1
l1 = l1.Next
} else {
cur.Next = l2
l2 = l2.Next
}
cur = cur.Next
}
if l1 != nil {
cur.Next = l1
} else if l2 != nil {
cur.Next = l2
}
return res.Next
}
Recommended Posts