[编程题] 合并两个有序链表--top100
作者:互联网
合并两个有序链表
题目描述
示例
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;
}
}
输出
标签:ListNode,val,编程,next,链表,l2,l1,top100 来源: https://www.cnblogs.com/jiyongjia/p/13252500.html