leetcode MergeTwoSortedList

来源:互联网 发布:丙肝化验单正常数据 编辑:程序博客网 时间:2024/06/03 20:55
/**
 * 
 * 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.

 * */


key Note

the solution is same with the merge sort.  and after the main loop, do not need to create two other loop to add the remains element, just point the pointer to the remains node

and the key, we can create a fake head. or compare the heads of two list to create the new list's head.

<span style="white-space:pre"></span>fake= new ListNode<Integer>(0);cur = fake;


public ListNode<Integer> soluction(ListNode<Integer> a, ListNode<Integer> b) {ListNode<Integer> cur;ListNode<Integer> root;if (a == null)return b;if (b == null)return a;if (a.value < b.value) {root = cur = a;a = a.next;} else {root = cur = b;b = b.next;}while (a != null && b != null) {if (a.value < b.value) {cur.next = a;a = a.next;} else {cur.next = b;b = b.next;}cur = cur.next;}if (a != null) {cur.next = a;}if (b != null) {cur.next = b;}return root;}




0 0