合并两个排序的链表

题目

牛客网

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

解题思路

  1. 双指针指向两个链表
  2. 循环选取最小值,加入结果集
1. public ListNode Merge(ListNode list1, ListNode list2) {
2. ListNode head = new ListNode(-1);
3. ListNode cursor = head;

5. while (list1 != null || list2 != null) {
6. if (list1 == null) {
7. while (list2 != null) {
8. cursor.next = list2;
9. cursor = cursor.next;
10. list2 = list2.next;
11. }

13. continue;
14. }

16. if (list2 == null) {
17. while (list1 != null) {
18. cursor.next = list1;
19. cursor = cursor.next;
20. list1 = list1.next;
21. }

23. continue;
24. }

26. if (list1.val < list2.val) {
27. cursor.next = list1;
28. cursor = cursor.next;

30. list1 = list1.next;
31. } else {
32. cursor.next = list2;
33. cursor = cursor.next;

35. list2 = list2.next;
36. }
37. }

39. return head.next;
40. }