两个单链表生成相加链表

public class AddList02 {

	public static Node addList01(Node head1,Node head2)
	{
		head1=reverseList(head1);
		head2=reverseList(head2);
		
		int n1=0;
		int n2=0;
		int n=0;
		int ca=0;	//进位
		
		Node node=null;
		Node pnode=null;
		while(head1!=null||head2!=null)
		{
			n1=head1==null?0:head1.data;
			n2=head2==null?0:head2.data;
			head1=head1.next;
			head2=head2.next;
			n=n1+n2+ca;
			node=new Node(n%10);
			node.next=pnode;
			pnode=node;
			ca=n/10;
		}
		
		if(n>=10)
		{
			node=new Node(n/10);
			node.next=pnode;
		}
		
		return node;
	}
	//实现链表的逆序
	public static Node reverseList(Node head)
	{
		Node pre=null;
		Node next=null;
		while(head!=null)
		{
			next=head.next;
			head.next=pre;
			pre=head;
			head=next;
		}
		return pre;
	}
}




public class CreateQueue {

	Node a=new Node(9);
	Node b=new Node(7);
	Node c=new Node(3);
	Node d=new Node(4);
	Node e=new Node(3);
	Node f=new Node(2);
	Node g=new Node(1);
	
	public CreateQueue()
	{
		a.next=b;
		b.next=c;
		c.next=d;
		d.next=e;
		e.next=f;
		f.next=g;
		g.next=null;
	}
}


public class CreateQueue02 {

	Node a=new Node(1);
	Node b=new Node(2);
	Node c=new Node(3);
	Node d=new Node(4);
	Node e=new Node(3);
	Node f=new Node(2);
	Node g=new Node(9);
	
	public CreateQueue02()
	{
		a.next=b;
		b.next=c;
		c.next=d;
		d.next=e;
		e.next=f;
		f.next=g;
		g.next=null;
	}
}

public class Test {


	public static void main(String[] args) {
	
	CreateQueue cq=new CreateQueue();
	CreateQueue02 cq2=new CreateQueue02();


		
	
		
		Node cur=cq.a;
		System.out.println("之前:");
		while(cur!=null)
		{
			System.out.print(cur.data+" ");
			cur=cur.next;
		}
		System.out.println();
		Node cur2=cq2.a;
		
		while(cur2!=null)
		{
			System.out.print(cur2.data+" ");
			cur2=cur2.next;
		}


		Node head=AddList02.addList01(cq.a, cq2.a);
		
		
		System.out.println();
		System.out.println("之后:");
	
		
			cur=head;
		while(cur!=null)
		{
			System.out.print(cur.data+" ");
			cur=cur.next;
		}
	}
	
	


}




public class Node {

	public int data;
	public Node next;
	public Node(int data)
	{
		this.data=data;
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值