21. Merge Two Sorted Lists
来源:互联网 发布:这位程序员四十岁了还 编辑:程序博客网 时间:2024/05/24 06:24
题目
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.
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 singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = new ListNode(0); ListNode p=head, p1=l1, p2=l2; while(p1!=null&&p2!=null){ if(p1.val<p2.val){p.next=p1; p1=p1.next;} else{p.next=p2; p2=p2.next;} p=p.next; } if(p1!=null) p.next = p1; else if(p2!=null) p.next=p2; return head.next; }}
python
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ head=ListNode(0); dup=head; while l1!=None and l2!=None : if l1.val < l2.val : dup.next=l1 l1 = l1.next dup = dup.next else: dup.next=l2 l2 = l2.next dup = dup.next if l2==None and l1!=None: dup.next=l1 elif l1==None and l2!=None: dup.next=l2 return head.next
0 0
- 21.Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21.Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- hdu 1874 畅通工程续
- Java异常处理方案【总结篇】
- 【LeetCode】Delete Node in a Linked List 解题报告
- 机器学习向量化练习
- ThoughtWorks的一道面试题
- 21. Merge Two Sorted Lists
- 解决mysql 不能插入中文 编码问题
- POJ 1275 差分约束系统+二分
- 记录PHP错误日志 display_errors与log_errors的区别
- Android View与GroupView原理以及其子类描述
- ConcurrentHashMap源码解析
- 数据库(mysql)简介
- 【日常】列表页优化历程
- 4.29日,世界安全日