Merge Two Sorted Lists

本文介绍了一种合并两个有序链表的方法,包括递归和非递归两种实现方式。递归方法通过比较两链表节点值来决定合并顺序,而非递归方法则通过循环迭代逐步完成合并。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

题意为合并两个有序链表。(这句话意思真是没看太懂,猜着先coding发现就是这个意思)

链表是面试中出现频率非常高的考点,这个题目还可以改进,去掉链表有序条件增加难度,然后就需要进行链表的排序,然后牵扯出快速排序,链表快速排序:http://blog.youkuaiyun.com/huruzun/article/details/25001085

所以链表快速排序又是一个经常问到的问题。(金山网络笔试+面试)

递归求法:

public class Solution {
	public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
		ListNode Pmerge = null;
		if(l1 == null){
			return l2;
		}
		if(l2 == null){
			return l1;
		}
		if(l1.val<l2.val){
			Pmerge = l1;
			Pmerge.next = mergeTwoLists(l1.next, l2);
		}else {
			Pmerge = l2;
			Pmerge.next = mergeTwoLists(l1, l2.next);
		}
		return Pmerge;
	}
}


非递归求法:采用非递归方法,这个方法不需要利用新的存储空间,只是去改变引用的指向

public class Solution {
    	public ListNode mergeTwoLists(ListNode l1, ListNode l2){
		ListNode Pmerge = null;
		if(l1 == null){
			return l2;
		}
		if(l2 == null){
			return l1;
		}
		if(l1.val<l2.val){
			Pmerge = l1;
			l1 = l1.next;
		}
		else {
			Pmerge = l2;
			l2 = l2.next;
		}
		ListNode head = Pmerge;
		while(l1!=null && l2!=null){
			if(l1.val<l2.val){
				Pmerge.next = l1;
				l1 = l1.next;
				Pmerge = Pmerge.next;
			}else {
				Pmerge.next = l2;
				l2 = l2.next;
				Pmerge = Pmerge.next;
			}
		}
		if(l1 == null){
			Pmerge.next = l2;
		}else {
			Pmerge.next = l1;
		}
		return head;
	}
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值