剑指offer面试题17-合并两个排序的链表

题目:

输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是按照递增排序的。

链表结构如下:

package com.aii.algorithm;

public class Node {
	int value;
	Node next;

	public Node(int value) {
		this.value = value;
	}

	@Override
	public String toString() {
		return "Node [value=" + value + ", next=" + next + "]";
	}

}


这个和归并排序差不多,只要记录好指针,不要让链表断掉就行了。

以及一些特殊情况的判断。


package com.aii.algorithm;

/**
 * 输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是按照递增排序的。
 * */
public class MergeLinkedList {
	// 循环的方法
	public Node merge(Node n1, Node n2) {
		// 用于记录头节点
		Node head = null;
		Node newCurrent = null;
		Node n1Current = n1;
		Node n2Current = n2;
		// 先处理第一个头结点。
		if (n1Current != null && n2Current != null) {
			if (n1Current.value > n2Current.value) {
				newCurrent = n2Current;
				n2Current = n2Current.next;
			} else {
				newCurrent = n1Current;
				n1Current = n1Current.next;
			}
		} else if (n1Current != null && n2Current == null) {
			newCurrent = n1Current;
			n1Current = n1Current.next;
		} else if (n1Current == null && n2Current != null) {
			newCurrent = n2Current;
			n2Current = n2Current.next;
		}
		// 记录,用于返回,防止被覆盖
		head = newCurrent;

		// 当2个链表都不为空的情况下,遍历取小的往合并都的链表放
		while (n1Current != null && n2Current != null) {
			if (n1Current.value > n2Current.value) {
				newCurrent.next = n2Current;
				newCurrent = n2Current;
				n2Current = n2Current.next;
			} else {
				newCurrent.next = n1Current;
				newCurrent = n1Current;
				n1Current = n1Current.next;
			}
		}
		// one is empty
		if (n1Current == null && n2Current != null) {
			newCurrent.next = n2Current;
		}
		if (n2Current == null && n1Current != null) {
			newCurrent.next = n1Current;
		}
		return head;
	}

	// 递归的方法
	public Node merge2(Node n1, Node n2) {
		if (n1 == null && n2 == null) {
			return null;
		}
		if (n1 == null && n2 != null) {
			return n2;
		}
		if (n1 != null && n2 == null) {
			return n1;
		}
		// n1!=null && n2!=null
		if (n1.value > n2.value) {
			n2.next = merge2(n1, n2.next);
			return n2;
		}
		n1.next = merge2(n1.next, n2);
		return n1;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值