/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
/*
链表的第一个公共结点:
1、定义一个辅助链表,新的链表的表头。并定义一个指针结点指向的是dummyNode
2、遍历链表
当两个链表都不为空的时候:
比较两个链表的结点的值,current.next指向比较小的结点值
当其中一个链表遍历完的时候,将剩下的结点跟进到后面就可以。
*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode dummyNode = new ListNode(0);
ListNode current = dummyNode;
while(list1 != null && list2 != null){
if(list1.val > list2.val){
current.next = list2;
current = current.next;
list2 = list2.next;
}else if(list1.val <= list2.val){
current.next = list1;
current = current.next;
list1 = list1.next;
}
}
while(list1 != null){
current.next = list1;
current = current.next;
list1 = list1.next;
}
while(list2 != null){
current.next = list2;
current = current.next;
list2 = list2.next;
}
return dummyNode.next;
}
}
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
/*
链表的第一个公共结点:
1、定义一个辅助链表,新的链表的表头。并定义一个指针结点指向的是dummyNode
2、遍历链表
当两个链表都不为空的时候:
比较两个链表的结点的值,current.next指向比较小的结点值
当其中一个链表遍历完的时候,将剩下的结点跟进到后面就可以。
*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode dummyNode = new ListNode(0);
ListNode current = dummyNode;
while(list1 != null && list2 != null){
if(list1.val > list2.val){
current.next = list2;
current = current.next;
list2 = list2.next;
}else if(list1.val <= list2.val){
current.next = list1;
current = current.next;
list1 = list1.next;
}
}
while(list1 != null){
current.next = list1;
current = current.next;
list1 = list1.next;
}
while(list2 != null){
current.next = list2;
current = current.next;
list2 = list2.next;
}
return dummyNode.next;
}
}