编程题-两个有序单链表合并

//两个有序链表合并
class Node{
	Node next;
	int data;
	public Node(int data){
		this.data = data;
	}
}

public class Test6{
	
		public static void main(String [] args){
			Node L1 = new Node(1);
			Node node1 = new Node(2);
			Node node2 = new Node(3);
			Node node3 = new Node(4);
			L1.next = node1;
			node1.next = node2;
			node2.next = node3;
			node3.next = null;
			
			Node L2 = new Node(2);
			Node node21 = new Node(3);
			Node node22 = new Node(5);
			Node node23 = new Node(9);
			Node node24 = new Node(10);
			L2.next = node21;
			node21.next = node22;
			node22.next = node23;
			node23.next = node24;
			node24.next = null;
			
			Node newHead = merge(L1,L2);
			
			while(newHead!= null){
				System.out.printf("%s ",newHead.data);
				newHead = newHead.next;
			
			
			}
		
		}
		
		public static Node merge(Node L1, Node L2){
			if(L1 == null){
				return L2;
			}
			
			if(L2 == null){
				return L1;
			}
					
			Node newHead = null; //新链表的头
			Node cur = new Node(-1);
			
			while(L1 != null && L2 != null){
				
				//取当前节点最小值加入新链表
				if(L1.data <= L2.data){
					
					cur.next = L1;
					cur = cur.next;
					L1 = L1.next;
					
					if(newHead == null){
						newHead = cur;
					}
				}else{
					cur.next = L2;
					cur = cur.next;
					L2 = L2.next;
					
					if(newHead == null){
						newHead = cur;
					}
				}
				
			}
			
			//判断哪个链表结尾还有节点没有遍历完
			if(L1 != null){
				cur.next = L1;
				L1 = L1.next;
				cur = cur.next;
			}
			
			if(L2 != null){
				cur.next = L2;
				L2 = L2.next;
				cur = cur.next;
			}
			
			return newHead;
			
		}
	


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值