您的位置:首页 > 其它

两个单链表生成相加链表

2016-12-13 21:32 387 查看
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;}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: