思路:
1.定义一个新的链表newHead保存合并后的链表,设置头结点为-1,头结点不能动,借助guard遍历
2.定义一个结点指针guard,实现newHead结点的遍历
3.循环比较list1,与list2的结点大小
1)循环条件,当list1,与list2不为空时,此处list1,与list2分别遍历各自链表
2)如果list2的值大,将guard指向list1结点,分别将guard和llist1往后移动
3)list1大,类似
4)当list1,或list2还有剩余时,将guard指向剩余链表
4.返回头结点newHead.next,去掉初始结点-1
/*
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 newHead=new ListNode(-1);//定义一个头结点
ListNode guard=newHead;//定义一个可以移动的指针
//重复判断
while(list1!=null && list2!=null){
if(list2.val>list1.val){
guard.next=list1;
list1=list1.next;
guard= guard.next;
} else {
guard.next=list2;
list2=list2.next;
guard= guard.next;
}
}
//判断剩余的,直接连接到guard下
if(list1 != null) {
guard.next = list1;
}
if(list2 != null) {
guard.next = list2;
}
return newHead.next;
}
}