• 两个链表合并不加入新的链表空间


    class LNode {
    	int value;
    	LNode next;
    
    	public LNode(int value, LNode next) {
    		this.value = value;
    		this.next = next;
    	}
    
    }
    
    public class MergeTowList {
    
    	public static void main(String[] args) {
    		LNode A5 = new LNode(21, null);
    		LNode A4 = new LNode(13, A5);
    		LNode A3 = new LNode(10, A4);
    		LNode A2 = new LNode(6, A3);
    		LNode A1 = new LNode(3, A2);
    
    		LNode B4 = new LNode(14, null);
    		LNode B3 = new LNode(12, B4);
    		LNode B2 = new LNode(6, B3);
    		LNode B1 = new LNode(4, B2);
    
    		LNode merge = mergeLinks(A1, B1);
    		System.out.println(123123);
    		while (merge != null) {
    			if (merge.next != null) {
    				System.out.print(merge.value + ",");
    			} else {
    				System.out.print(merge.value);
    			}
    
    			merge = merge.next;
    		}
    
    	}
    
    	public static LNode mergeLinks(LNode head1,LNode head2){
    		if(head1==null){
    			return head2;
    		}
    		if(head2==null){
    			return head1;
    		}
    		LNode head;
    		if(head1.value>head2.value){
    			head = head2;
    			head2=head2.next;
    		}else{
    			head = head1;
    			head1=head1.next;
    		}
    		LNode current=head;//current指向新的链表的最后一个节点
    		while(head1!=null && head2!=null){
    			if(head1.value>head2.value){
    				current.next=head2;
    				current=head2;
    				head2=head2.next;
    			}else{
    				current.next=head1;
    				current = head1;
    				head1=head1.next;
    			}
    		}
    		if(head1!=null){//把listA的全部插入到current后面
    			current.next=head1;
    		}
    		if(head2!=null){
    			current.next=head2;
    		}
    		
    		return head;
    		
    	}
    
    }
    
  • 相关阅读:
    福建省队集训被虐记——DAY1
    bzoj1755 [Usaco2005 qua]Bank Interest
    bzoj1754 [Usaco2005 qua]Bull Math
    bzoj1753 [Usaco2005 qua]Who's in the Middle
    wikioi1369 xth 砍树
    wikioi1191 数轴染色
    bzoj1189 [HNOI2007]紧急疏散evacuate
    POJ 3734 Blocks(矩阵快速幂+矩阵递推式)
    斐波那契+大数相加
    矩阵的快速幂
  • 原文地址:https://www.cnblogs.com/chengpeng15/p/6081976.html
Copyright © 2020-2023  润新知