标签:span 表头 一个 长度 value 关系 合并链表 变量 his
给定两个有序单链表的头节点head1 和 head2 ,请合并两个有序链表,合并后的链表依然有序,并返回合并后链表的头节点
假设两个链表长度为M和N 直接给出时间复杂度为(M+N) 额外空间复杂度O(1)
1 如果两个链表中一个为空 则无需合并 返回另一个的链表头节点
2 比较head1 和 head2 的值,小的是合并链表的头节点,记为head 在之后的步骤里 哪个链表的头节点值更小,另一个链表的所有节点都会一次插入到这个链表中
3不妨设head节点所在的链表1, 另一个链表2,1和2都从头部开始一起遍历,比较每次遍历的两个节点的值,记为 cur1 和 cur2 然后根据大小关系做出不同的调整 同时用一个变量pre表示上次比较时值较小的节点
如果两个链表有一个结束,就进入下一步
如果链表1先走完,此时cur1=null, pre为链表1的最后一个节点,那么就把pre的next指针指向链表2的当前的节点cur2。
返回合并后链表的头节点head
代码:
package TT;
public class Test114 {
	public class Node{
		public int value;
		public Node next;
		
		public Node(int data){
			this.value=data;
		}
		
	}
	
	public Node merge(Node head1, Node head2){
		if(head1==null || head2==null){
			  return head1 != null ? head1 : head2;
		}
		Node head = head1.value < head2.value ? head1 : head2;
		Node cur1 = head==head1 ? head1 : head2;
		Node cur2 = head==head1? head2: head1;
		Node pre = null;
		Node next =null;
		
		while(cur1 != null && cur2 != null){
			if(cur1.value <= cur2.value){
				pre=cur1;
				cur1=cur1.next;
			}else {
				next=cur2.next;
				pre.next=cur2;
				cur2.next=cur1;
				pre=cur2;
				cur2=next;
			}
		}
		pre.next=cur1==null ? cur2 : cur1;
		return head;
		
	}
	
	
	
}
标签:span 表头 一个 长度 value 关系 合并链表 变量 his
原文地址:http://www.cnblogs.com/toov5/p/7506589.html