合并两个有序链表

链表的基本构造:

public class ListNode {
	public int val;
	public ListNode next;

	public ListNode(int val, ListNode next) {
		super();
		this.val = val;
		this.next = next;
	}

	public ListNode(int val) {
		super();
		this.val = val;
	}

	public static ListNode arrayToList(int[] arr) {
		ListNode head = new ListNode(0);
		ListNode p = head;
		for(int value : arr){
			p.next = new ListNode(value);
			p = p.next;
		}
		return head.next;
	}
	
	public static void printList(ListNode head){
		ListNode p = head;
		while(p != null){
			System.out.print(p.val + " ");
			p = p.next;
		}
		System.out.println();
	}
}

2.两个链表的合并代码:

public class 合并两个有序链表 {
	public static void main(String[] args) {
		int[] array1 = { 1, 3, 7, 8 };
		ListNode head1 = ListNode.arrayToList(array1);
		ListNode.printList(head1);

		int[] array2 = { 2, 4, 5, 9 };
		ListNode head2 = ListNode.arrayToList(array2);
		ListNode.printList(head2);

		ListNode.printList(mergeList(head1, head2));
	}

	private static ListNode mergeList(ListNode head1, ListNode head2) {
		if (head1 == null && head2 == null) {
			return null; // 如果两个链表都为空
		}
		if (head1 == null) {
			return head2;
		}
		if (head2 == null) {
			return head1;
		}
		/**
		 * 新链表的头结点 一开始,我们让current结点指向head1和head2中较小的数据,得到head结点
		 */
		ListNode head;
		ListNode current;
		if (head1.val < head2.val) {
			head = head1;
			current = head1;
			head1 = head1.next;
		} else {
			head = head2;
			current = head2;
			head2 = head2.next;
		}

		while (head1 != null && head2 != null) {
			if (head1.val < head2.val) {
				current.next = head1; // 新链表中,current指针的下一个结点对应较小的那个数据
				current = current.next; // current指针下移
				head1 = head1.next;
			} else {
				current.next = head2;
				current = current.next;
				head2 = head2.next;
			}
		}
		// 合并剩余的元素
		if (head1 != null) {
			current.next = head1;
		}
		if (head2 != null) {
			current.next = head2;
		}

		return head;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值