合并两个排序的链表
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
我的思路
因为两个链表都是有序的,因此只要以一个链表为基准,把另一个链表的值依次插入即可
我的解决办法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import java.util.ArrayList; public class Solution { public ListNode pList1; public ListNode addNode(int val){ if(pList1.next == null){ pList1.next = new ListNode(val); return pList1.next; } if(pList1.next.val>=val){ ListNode newListNode = new ListNode(val); newListNode.next = pList1.next; pList1.next = newListNode; return newListNode; } pList1 = pList1.next; return addNode(val); } public ListNode Merge(ListNode list1,ListNode list2) { pList1 = list1; while(list2 != null){ addNode(list2.val); list2 = list2.next; } return list1; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| function Merge(pHead1, pHead2) { if(pHead1!=null&& pHead2!=null && pHead1.val >= pHead2.val){ let newListNode = new ListNode(pHead2.val) newListNode.next = pHead1 pHead1 = newListNode pHead2 = pHead2.next } let head1 = pHead1 function add(val){ if(head1.next == null){ head1.next = new ListNode(val) return; } if(head1.next.val>=val){ let newListNode = new ListNode(val) newListNode.next = head1.next head1.next = newListNode return; } head1 = head1.next return add(val) } while(pHead2!=null){ add(pHead2.val) pHead2=pHead2.next } return pHead1 }
|