本文主要是介绍leetcode21. 合并两个有序链表(python,java),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.问题
原题
2.解答
python:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/
// O(m+n);遍历,比较两个链表数值,
class Solution {public ListNode mergeTwoLists(ListNode l1, ListNode l2) {ListNode node1 = l1;ListNode node2 = l2;if(node1== null) return l2;if(node2 == null) return l1;ListNode dummy = new ListNode(0);ListNode res = dummy;while(node1!=null && node2!=null){// System.out.println(node1.val);int value = node1.val;while(node2!= null){if(node2.val == value){res.next = node1;node1 = node1.next;res = res.next;res.next = node2;node2 = node2.next;break;}else if(node2.val < value){res.next = node2;node2 = node2.next;break;} else if(node2.val > value){res.next = node1;node1 = node1.next;break;}}res = res.next;}res.next = node1== null? node2:node1;return dummy.next;}
}
java:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/
class Solution {public ListNode mergeTwoLists(ListNode l1, ListNode l2) {ListNode node1 = l1;ListNode node2 = l2;if(node1== null) return l2;if(node2 == null) return l1;ListNode dummy = new ListNode(0);ListNode res = dummy;while(node1!=null && node2!=null){// System.out.println(node1.val);int value = node1.val;while(node2!= null){if(node2.val == value){res.next = node1;node1 = node1.next;res = res.next;res.next = node2;node2 = node2.next;break;}else if(node2.val < value){res.next = node2;node2 = node2.next;break;} else if(node2.val > value){res.next = node1;node1 = node1.next;break;}}res = res.next;}res.next = node1== null? node2:node1;return dummy.next;}
}
这篇关于leetcode21. 合并两个有序链表(python,java)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!