LeetCode刷题day021 (Jieky)

LeetCode第21题

/*
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.

Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
*/
class ListNode{
     
	int val;
	ListNode next;
	ListNode(){
     };
	ListNode(int val){
     this.val=val;}
	ListNode(int val, ListNode next) {
      this.val = val; this.next = next; }
}

public class MergeTwoSortedLists{
     
	public static void main(String[] args){
     
		ListNode node1_1 = new ListNode(1);
		ListNode node1_2 = new ListNode(2);
		ListNode node1_3 = new ListNode(4);
		node1_1.next = node1_2;
		node1_2.next = node1_3;
		
		ListNode node2_1 = new ListNode(1);
		ListNode node2_2 = new ListNode(3);
		ListNode node2_3 = new ListNode(4);
		node2_1.next = node2_2;
		node2_2.next = node2_3;
		
		MergeTwoSortedLists mtsl = new MergeTwoSortedLists();
		ListNode result = mtsl.mergeTwoLists(node1_1,node2_1);
		
		while(result != null){
     
			System.out.println(result.val);
			result = result.next;
		}
	}
	
	// 递归需要的资源更多
	public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
     
		if (l1 == null) return l2;
		if (l2 == null) return l1;
		
		if (l1.val < l2.val){
     
			l1.next = mergeTwoLists(l1.next,l2);
			return l1;
		} else{
     
			l2.next = mergeTwoLists(l1,l2.next);
			return l2;
		}
	}
	
	public ListNode mergeTwoLists01(ListNode l1, ListNode l2) {
     
		if (l1 == null) return l2;
		if (l2 == null) return l1;
		
		ListNode head = new ListNode();
		ListNode end = new ListNode();
		
		// 初始化头指针
		if (l1.val < l2.val){
     
			head.next = l1;
			l1 = l1.next;
		}else{
     
			head.next = l2;
			l2 = l2.next;
		}
		// 初始化当前节点指针
		end = head.next;
		
		while(l1 != null || l2 != null){
     
			// 当一个链表为null,剩下的链表直接接上
			if(l1 == null || l2 == null){
     
				end.next = l1 == null ? l2:l1;
				break;
			}
			
			// 接上当前小的节点
			if (l1.val < l2.val){
     
				end.next = l1;
				l1 = l1.next;
			}else{
     
				end.next = l2;
				l2 = l2.next;
			} 
			
			// end永远指向最后一个节点
			end = end.next;
		}
		
		return head.next;
	}
}

你可能感兴趣的:(LeetCode,java,leetcode)