BM4 题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
总结进步:
👍,自己做出来了,算是真正理解链表了!!!
经过对链表的深入理解,现在可以自己做出链表合并的代码了!!well done~~!为了你进步感到高兴!
解题思路:
1、定义两个临时的链表头,newHead 、curr 指向 new ListNode(-1),
1)newHead用于返回合并后的链表头
2)curr用于遍历添加节点到新链表头
2、使用while循环,驱动pHead1,pHead2的比较和遍历新节点到cur的尾巴
3、遍历的过程中,所有的链表都要 xxx = xxx.next 更新到下个节点进行填充或者取值比较,
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ public ListNode Merge (ListNode pHead1, ListNode pHead2) { // write code here if(pHead1==null || pHead2==null) { return pHead1; } ListNode newHead = new ListNode(-1); ListNode curr = newHead; while(pHead1!=null && pHead2!=null) { if(pHead1.val<pHead2.val) { curr.next = pHead1; pHead1 = pHead1.next; } else { curr.next = pHead2; pHead2 = pHead2.next; } curr = curr.next; } if(pHead1!=null) { curr.next = pHead1; } else { curr.next = pHead2; } return newHead.next; } }