链表-Merge Two Sorted Lists(合并两个单项链表)

问题描述:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

思考:

最开始以为就是两个链表简答的合并就ok,自己确实差啊,后来想想有些细节,合并后的链表是递增的,每次添加的节点是两个链表中当前节点的最小值,还有就是两个链表也不一定相等。

代码(java):

public class MergeTwoSortedLists {

	static public class ListNode {
		int val;
		ListNode next;
		ListNode(int x) { 
			val = x;
		}
	}


	public ListNode mergeTwoLists(ListNode l1, ListNode l2) {


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


		ListNode current,left,right,head;//current是最近添加的节点,也就是当前工作节点,head表示头结点
		
		left = l1;
		right = l2;
		
		
		//找一个最小值作为头结点,假设两个链表都是有序链表,所以l1和l2都是所在链表的最小值
		if(l1.val<= l2.val){
			head = l1;
			left = left.next;
		}
		else{
			head = l2;
			right = right.next;
		}
		
		
		current = head;
		
		
		//寻找right和left的小值作为当前节点的下一个节点
		while(left != null && right != null){
			if(left.val <= right.val ){
				current.next = left;
				current = left;
				left = left.next;
			}
			else{
				current.next = right;
				current = right;
				right = right.next;
			}
		}
		
		
		
		if(left == null){
			while(right != null){
				current.next = right;
				current = right;
				right = right.next;
			}
		}
		
		if(right == null){
			while(left != null){
				current.next = left;
				current = left;
				left = left.next;
			}
		}


		return head;
	}



}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值