合并两个排序的链表(java)

我GitHub上的:剑指offer题解​​​​​​​

合并两个排序的链表

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则

思路一:新建一个链表,从前往后遍历两个链表,谁小谁先进新链表。采用递归的方式。

思路二:思路一采用的是递归的方法,思路二采用非递归的方法

思路一

新建一个链表,从前往后遍历两个链表,谁小谁先进新链表。采用递归的方式。

public static ListNode listMerge(ListNode list1, ListNode list2){
	if (list1 == null) return list2;//判断某个链表为空就返回另一个链表。
	if (list2 == null) return list1;
	ListNode mergeList = null;//定义一个链表作为返回值
	if (list1.val <= list2.val) {//如果list1的值比较小,就先把list1赋值给mergeList
		mergeList = list1;
		mergeList.next = listMerge(list1.next, list2);//做递归,求链表下一个结点的值
	}
	else {//如果list2的值比较小,就先把list1赋值给mergeList
		mergeList = list2;
		mergeList.next = listMerge(list1, list2.next);//做递归,求链表下一个结点的值
	}
	return mergeList;
}

可以简化一下,用三目运算符

mergeList = list1.val > list2.val ? list2:list1;
mergeList.next = list1.val > list2.val ? listMerge(list1, list2.next):listMerge(list1.next, list2);

 

思路二

 

思路一采用的是递归的方法,思路二采用非递归的方法。

public static ListNode listMerge2(ListNode list1, ListNode list2){
	if (list1 == null) return list2;//判断某个链表为空就返回另一个链表。
	if (list2 == null) return list1;
	
	
	ListNode mergeList = new ListNode(0);//为什么不是为null.因为下面要有mergeList.next
//	ListNode mergeList = null;
	ListNode temp1 = list1;
	ListNode temp2 = list2;
	ListNode head = mergeList;//保留其指针位置
	while(temp1 != null && temp2 != null){
		if (temp1.val <= temp2.val) {
			mergeList.next = temp1;
			mergeList = mergeList.next;
			temp1 = temp1.next;
		}
		else {//如果list2的值比较小,就先把list1赋值给mergeList
			mergeList.next = temp2;
			mergeList = mergeList.next;
			temp2 = temp2.next;
		}
	}//while end.其中一条链表已经遍历完
	if (temp1 != null) {
		mergeList.next = temp1;
		mergeList = mergeList.next;
		temp1 = temp1.next;
	}
	if (temp2 != null) {
		mergeList.next = temp2;
		mergeList = mergeList.next;
		temp2 = temp2.next;
	}
	mergeList = head.next;
	return mergeList;
}

 

测试函数:

 

public static void main(String[] args) {
	ListNode listNode1 = new ListNode(1);
	ListNode listNode2 = new ListNode(6);
	ListNode listNode3 = new ListNode(9);
	ListNode listNode4 = new ListNode(11);
	ListNode listNode5 = new ListNode(12);
	listNode1.next = listNode2;
	listNode2.next = listNode3;
	listNode3.next = listNode4;
	listNode4.next = listNode5;
		
	ListNode listNode6 = new ListNode(1);
	ListNode listNode7 = new ListNode(2);
	ListNode listNode8 = new ListNode(4);
	ListNode listNode9 = new ListNode(10);
	ListNode listNode10 = new ListNode(12);
	ListNode listNode11 = new ListNode(13);
	listNode6.next = listNode7;
	listNode7.next = listNode8;
	listNode8.next = listNode9;
	listNode9.next = listNode10;
	listNode10.next = listNode11;
		
	ListNode merge = listMerge2(listNode1, listNode6);
	ListNode head = merge;
	while (head != null) {
		System.out.print(head.val + " ");
		head = head.next;
			
	}	}

 

 

 

你可能感兴趣的:(剑指offer)