题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
有链表为空时,直接连接不为空的链表;都不为空时比较大小,跟新指针
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode Merge(ListNode list1, ListNode list2) { ListNode res = new ListNode(-1); ListNode resNext = res.next; int j = 0; while (list1 != null && list2 != null) { if (list1.val < list2.val) { res.next = list1; list1 = list1.next; res = res.next; j++; } else { res.next = list2; list2 = list2.next; res = res.next; j++; } if (j == 1) resNext = res; } if (list1 == null && list2 != null) { res.next = list2; res = res.next; j++; if (j == 1) resNext = res; } if ( list2 == null && list1 != null ) { res.next = list1; res = res.next; j++; if (j == 1) resNext = res; } return resNext; } }