Merge Two Sorted Lists
来源:互联网 发布:snmp trap 端口号 编辑:程序博客网 时间:2024/06/05 18:14
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
java
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */public class Solution { /* * @param l1: ListNode l1 is the head of the linked list * @param l2: ListNode l2 is the head of the linked list * @return: ListNode head of linked list */ public ListNode mergeTwoLists(ListNode l1, ListNode l2) { // write your code here if (l1 == null && l2 == null) { return null; } if (l1 == null && l2 != null) { return l2; } if (l1 != null && l2 == null) { return l1; } ListNode dummy = new ListNode(0); ListNode head = dummy; while (l1 != null && l2 != null) { if (l1.val < l2.val) { dummy.next = l1; dummy = dummy.next; l1 = l1.next; } else { dummy.next = l2; dummy = dummy.next; l2 = l2.next; } } while (l1 != null) { dummy.next = l1; dummy = dummy.next; l1 = l1.next; } while (l2 != null) { dummy.next = l2; dummy = dummy.next; l2 = l2.next; } return head.next; }}python
"""Definition of ListNodeclass ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next"""class Solution: """ @param: l1: ListNode l1 is the head of the linked list @param: l2: ListNode l2 is the head of the linked list @return: ListNode head of linked list """ def mergeTwoLists(self, l1, l2): # write your code here if l1 is None and l2 is None: return None if l1 is None and l2 is not None: return l2 if l1 is not None and l2 is None: return l1 dummy = ListNode(0) head = dummy while l1 is not None and l2 is not None: if l1.val < l2.val: head.next = l1 l1 = l1.next else: head.next = l2 l2 = l2.next head = head.next while l1 is not None: head.next = l1 l1 = l1.next head = head.next while l2 is not None: head.next = l2 l2 = l2.next head = head.next return dummy.next
阅读全文
1 0
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- 爬虫笔记(9/28)-------多线程
- springboot vue 登陆发送请求(跨域问题)02
- Insertion Sort(插入排序)
- 信息管理系统-数据库
- Stm32用寄存器还是库函数
- Merge Two Sorted Lists
- Jin Ge Jin Qu [h]ao,Uva 12563
- bzoj2795[Poi2012]A Horrible Poem 暴力hash
- 一直接收键盘字符,如果是小写字符就输出对应的大写字符,如果接收的是大写字符,就输出对应的小写字符,如果是数字不输出
- [agc015d]A or...or B Problem
- hashMap非线程安全问题和concurrenthashmap线程安全的比较
- gson转json格式
- centos 安装 docker docker-compose
- 入门机器学习,必须掌握这些数据技能