190505打卡:合并两个有序的单链表

题目描述:
给定两个有序单链表的头结点head1和head2,请合并两个有序链表,合并后的链表依然有序,并返回合并后链表的头结点。
例如:
0—>2—>3—>7—>NULL
1—>3—>5—>7—>9—>NULL
合并后的链表为:0—>1—>2—>3—>3—>5—>7—>7—>9—>NULL
要求:假设两个链表的长度分别为M和N,时间复杂度为O(M + N),额外空间复杂度O(1)

思路:有两种实现方式,一种是将一个有序的链表插入到另一个头结点较小的有序的链表中,插入节点时,要注意记录插入位置的前一个和后一个节点,并且要注意一下在一下的实现方式中,如何在两个链表的头结点值的大小不确定的情况中,寻找值较小的头结点,第二种是依次比较两个链表节点值的大小,将较小的节点从原来节点上面摘下来,重新组成一个有序的链表

public class Code_018_MergeList {
	public static class Node {
		public int data;
		public Node next;
		
		public Node(int data) {
			this.data = data;
		}
	}
	
	//第二种实现方式
	public static Node merge1(Node head1, Node head2) {
		if (head1 == null || head2 == null) {
			return head1 != null ? head1 : head2;
		}
		
		Node dummyHead = new Node(-1);	//虚拟头结点
		Node cur = dummyHead;
		while(head1 != null && head2 != null) {
			if (head1.data <= head2.data) {
				cur.next = head1;
				cur = head1;
				head1 = head1.next;
				cur.next = null;
			} else {
				cur.next = head2;
				cur = head2;
				head2 = head2.next;
				cur.next = null;
			}
		}
		
		cur.next = head1 == null ? head2 : head1;
		
		return dummyHead.next;
	}
	
	//第一种实现方式
	public static Node merge2(Node head1, Node head2) {
		if (head1 == null || head2 == null) {
			return head1 != null ? head1 : head2;
		}
		
		Node head = head1.data <= head2.data ? head1 : head2;
		Node cur1 = head == head1 ? head1 : head2;
		Node cur2 = head == head1 ? head2 : head1;
		Node prev = null;
		Node next = null;
		while(cur1 != null && cur2 != null) {
			if (cur1.data <= cur2.data) {
				prev = cur1;
				cur1 = cur1.next;
			} else {
				next = cur2.next;
				prev.next = cur2;
				cur2.next = cur1;
				prev = cur2;
				cur2 = next;
			}
		}
		
		prev.next = cur1 == null ? cur2 : cur1;
		
		return head;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值