【剑指offer】合并两个有序的链表

【文章结构】:

1 实现方法1--自己编写  

2 参考剑指offer代码


【我的解题思路】

1 编写一个函数,可以在链表尾部加入节点(linklist.addNodeAtTail(pNew,pNow))

public Node addNodeAtTail(Node newNode,Node currNode){
		Node pNew=currNode;
		if(currNode==null)
			{ pNew=newNode;
			  head=pNew;
			  tail=pNew;
			if(newNode!=null)
				{size++;
				currNode=pNew;}
			
			}
		else if(newNode!=null){
			{
			currNode.next=newNode;
			currNode=newNode;
			tail=newNode;
			size++;
			}
		}
		   return currNode;
			}
2 比较两个有序链表的第一个值,并将最小值添加到新链表中

public void mergeLinklist(Node pHead1,Node pHead2){
		
	
		Node cuNode=null;
		while(pHead1!=null||pHead2!=null){
			if(pHead1==null||pHead2!=null&&pHead1.value>=pHead2.value)
				{
				cuNode=addNodeAtTail(pHead2,cuNode);
				pHead2=pHead2.next;
				}
			else if(pHead2==null||pHead1!=null&&pHead1.value<=pHead2.value)
			{ cuNode=addNodeAtTail(pHead1,cuNode);
			  pHead1=pHead1.next;
				
			}
			
		}	
测试程序及运行结果:

MyLinkList linklist6=new MyLinkList();
		//Node addNodeAtTail(Node newNode,Node currNode)
		Node p1=linklist4.head;
		Node p2=linklist5.head;
		//mergeLinklist(p1,p2,linklist6);
		linklist6.mergeLinklist(p1, p2);
		//linklist6.mergeLinklist(p1, null);
		linklist6.print(linklist6.head);
the elements in the list :
3 4 5 7 14 
the elements in the list :
2 3 6 11 
the elements in the list :
2 3 3 4 5 6 7 11 14 


【参考答案方法:】

//答案中采用递归方法,递归方法就不用while循环了。。。,之前还一直担心递归结果回去会返回链表的尾节点。。。,哎 学艺不精!


	public Node mergeLinklist_Ans(Node pHead1,Node pHead2){
		if(pHead1==null)
			return pHead2;
		if(pHead2==null)
			return pHead1;
		Node mergeNode=null;
		if(pHead1.value>=pHead2.value){
			mergeNode=pHead2;
			mergeNode.next=mergeLinklist_Ans( pHead1,pHead2.next);
		}
		else{
			mergeNode=pHead1;
			mergeNode.next=mergeLinklist_Ans( pHead1.next,pHead2);
		}
		
		return mergeNode;
	}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值