标签:pre val this ted java solution 有一个 problems node
题目描述
示例
Java代码
/**
* 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; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//最终的生成的链表的头结点
ListNode head = new ListNode(-1);
ListNode reshead = head; //最终链表的哨兵
ListNode l1head = l1; //l1链表的哨兵
ListNode l2head = l2; ///l2链表的哨兵
//当有一个链表到头的时候就退出
while(!(l1head==null || l2head==null)){
//当l1链表的值小于l2链表的值,就把它挂在最终的链表上
if(l1head.val<=l2head.val){
reshead.next = l1head;
l1head = l1head.next;
reshead = reshead.next;
}else{//反之
reshead.next = l2head;
l2head = l2head.next;
reshead = reshead.next;
}
}
//判断剩余的是哪个链表没取完,直接挂在head链表后
reshead.next = l1head==null ? l2head : l1head;
//返回最终的链表
return head.next;
}
}
输出
标签:pre val this ted java solution 有一个 problems node
原文地址:https://www.cnblogs.com/jiyongjia/p/13252500.html