您当前的位置: 首页 >  链表
  • 0浏览

    0关注

    674博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

合并两个有序链表

沙漠一只雕得儿得儿 发布时间:2017-05-23 16:22:01 ,浏览量:0

链表的基本构造:

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;
	}
}

关注
打赏
1657159701
查看更多评论
立即登录/注册

微信扫码登录

0.0569s