题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
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) {
//先判断是否有为空的链表,一一进行返回
if(pHead1==null){
return pHead2;
}
if(pHead2==null){
return pHead1;
}
if(pHead1==null&&pHead2==null){
return null;
}
//创建一个pHead3链表来存pHead1,pHead2链表
ListNode phead3 =new ListNode(0);
//给phead3创建一个当前指针
ListNode cur=phead3;
//将pHead1、pHead2插入到phead3中
while(true){
//如果pHead1链表空了,那么将pHead2连到phead3尾部,此时完成合并,返回phead3
if(pHead1==null){
cur.next=pHead2;
return phead3.next;
}
//如果pHead2链表空了,那么将pHead1连到phead3尾部,此时完成合并,返回phead3
if(pHead2==null){
cur.next=pHead1;
return phead3.next;
}
//如果pHead1.val<=pHead2.val,则将pHead1当前节点连到pHead3尾部,pHead1指针后移
if(pHead1.val<=pHead2.val){
cur.next=pHead1;
pHead1=pHead1.next;
}else{
cur.next=pHead2;
pHead2=pHead2.next;
}
cur=cur.next;
}
}
}
