Leecode no.21 合并两个有序链表

package com.example.demo.leecode;

/**
* 合并两个有序链表
* @Date 2020/12/11
* @author Tang
*
* 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
*
* /**
* * Definition for singly-linked list.
* * public class ListNode {
* * int val;
* * ListNode next;
* * ListNode() {}
* * ListNode(int val) { this.val = val; }
* * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* * }
*
*/
public class MergeTwoSortedLists {

public ListNode execute(ListNode l1, ListNode l2){

if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}

ListNode firstNode;

ListNode endNode;

//先确定头节点
if(l1.val <= l2.val){
firstNode = l1;
endNode = firstNode;
l1 = l1.next;
}else{
firstNode = l2;
endNode = firstNode;
l2 = l2.next;
}

while(true){
if(l1 == null || l2 == null){
break;
}
if(l1.val <= l2.val){
endNode.next = l1;
endNode = l1;
l1 = l1.next;
}else{
endNode.next = l2;
endNode = l2;
l2 = l2.next;
}
}

while(l1 != null){
endNode.next = l1;
endNode = l1;
l1 = l1.next;
}
while(l2 != null){
endNode.next = l2;
endNode = l2;
l2 = l2.next;
}
return firstNode;


}

public static void main(String[] args) {

ListNode left1 = new ListNode(1);
ListNode left2 = new ListNode(2);
ListNode left3 = new ListNode(5);
ListNode left4 = new ListNode(6);
ListNode left5 = new ListNode(6);
ListNode left6 = new ListNode(8);
left1.next = left2;
left2.next = left3;
left3.next = left4;
left4.next = left5;
left5.next = left6;

ListNode right1 = new ListNode(1);
ListNode right2 = new ListNode(2);
ListNode right3 = new ListNode(2);
ListNode right4 = new ListNode(7);
right1.next = right2;
right2.next = right3;
right3.next = right4;


ListNode result = new MergeTwoSortedLists().execute(left1, right1);
System.out.println(result.val);
while(result.hasNext()){
result = result.next;
System.out.println(result.val);
}

}


}

class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
boolean hasNext(){
return next != null;
}

}
posted @ 2020-12-11 11:54  六小扛把子  阅读(90)  评论(0编辑  收藏  举报