赞
踩
简单算法 合并有序链表(java)
描述
将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的,且合并后新链表依然有序。
示例1
输入:
{1},{2}
返回值:
{1,2}
想法:利用两个节点,1为头节点,2为连接链表的中间节点,通过不断判断来连接两个链表
代码:
public ListNode mergeTwoLists (ListNode l1, ListNode l2) { if(l1 == null) return l2; if(l2 == null) return l1; ListNode head = (l1.val >= l2.val) ? l2: l1; ListNode nex = head; if( head == l1 ) l1 = l1.next; else l2 = l2.next; while(l1 !=null && l2 !=null){ if(l1.val >= l2.val){ nex.next = l2; l2 = l2.next; }else{ nex.next = l1; l1 = l1.next; } nex = nex.next; } nex.next = (l1 == null)? l2 : l1; return head; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。