Advertisement
Guest User

Grokking 220

a guest
May 25th, 2022
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. class Solution {
  2. ListNode mergeTwoLists(ListNode list1, ListNode list2) {
  3. ListNode dummy = new ListNode();
  4. ListNode cur = dummy;
  5. while (list1 != null && list2 != null) {
  6. if (list1.val > list2.val) {
  7. cur.next = list2;
  8. cur = list2;
  9. list2 = list2.next;
  10. } else {
  11. cur.next = list1;
  12. cur = list1;
  13. list1 = list1.next;
  14. }
  15. }
  16.  
  17. while (list1 != null) {
  18. cur.next = list1;
  19. cur = list1;
  20. list1 = list1.next;
  21. }
  22.  
  23. while (list2 != null) {
  24. cur.next = list2;
  25. cur = list2;
  26. list2 = list2.next;
  27. }
  28.  
  29. return dummy.next;
  30. }
  31.  
  32. public ListNode mergeKLists(ListNode[] lists) {
  33. if (lists.length == 0) {
  34. return null;
  35. }
  36. int loopCount = 1;
  37. while (loopCount < lists.length) {
  38. for (int i = 0; i + loopCount < lists.length; i += loopCount*2) {
  39. lists[i] = mergeTwoLists(lists[i], lists[i + loopCount]);
  40. }
  41. loopCount *= 2;
  42. }
  43.  
  44. return lists[0];
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement