数据结构--合并两个链表并且有序

 

	public static SingleLinkedList mergeLinked(HeroNode head1, HeroNode head2) {

		HeroNode temp1 = head1.next;
		HeroNode temp2 = head2.next;
		HeroNode next1 = null;
		HeroNode next2 = null;
		HeroNode tail = null;

		SingleLinkedList s3 = new SingleLinkedList();
		HeroNode head3 = s3.getHead();
		tail = head3;

		while (temp1 != null && temp2 != null) {
			if (temp1.no > temp2.no) {
				if (head3.next != null) {
					next2 = temp2.next;
					head2.next = next2;

					tail.next = temp2;
					temp2.next= null;
					tail = temp2;
					
					temp2 = next2;

				} else {
					// 新链表为空的情况。
					next2 = temp2.next;
					head2.next = next2;

					head3.next = temp2;
					temp2 = null;
					tail = temp2;

					temp2 = next2;
				}
			} else {
				// 如果新链表中不为空
				if (head3.next != null) {
					next1 = temp1.next;
					head1.next = next1;

					tail.next = temp1;
					temp1.next= null;
					tail = temp1;
					
					temp1 = next1;
				} else {
					// 新链表为空的情况。
					next1 = temp1.next;
					head1.next = next1;

					head3.next = temp1;
					temp1 = null;
					tail = head3.next;

					temp1 = next1;
				}
			}
		}
		return s3;
	}

解析:

1.首先定义2个链表,还要定义一个排序后的链表

其中将要排序的链表为S1 和 S2 ,还有一个排序链表S3

大致的思路就是:

  利用两个赋值变量(学过C语言的应该是知道指针,都是方便对链表进行操作,java中没有指针),如上图所示,我定义了两个辅助变量,temp1 指向 S1 链表的头结点的下一个结点(当然也可以没有头结点,看个人的设计),也就是指向1的辅助变量,temp2指向S2链表的头结点的下一个结点,也就是指向3的辅助变量。还有一个操作S3的辅助变量tail,初始指针头结点。

核心思想就是:两个辅助变量所指向的节点的值进行比较,如上图中  1 和 3 进行比较,显然 1 比 3 小,我就将1 放入排序后的链表S3中。当然此处还要考虑排序链表S3中是否有元素(为什么要考虑这种情况呢? 因为如果链表S3中如果有元素的话,元素插入的方式也是不一样的)

举例:排序链表中没有元素的情况:(比较1和3 ,显然1小,将1放入S3中,此时S3中没有结点(不包含头结点))

核心代码:

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值