你有两个用链表代表的整数,其中每个点包含一个整数。证书存储按照在原来证书中想法的顺序,是的第一个数字位于链表的开头,写出一个函数将两个整数相加,用链表返回和。(Tencent)
主要是代码风格的查看,
觉得有时间还是有必要将这些基础的知识捡一捡
public class LinkedListSummary {
//节点构成,注意是用static修饰的内部内的方式,方便调用不用new一个外部类
public static class Node{
int value;
Node next;
public Node(int n){
this.value=n;
this.next=null;
}
}
public static void main(String[] args) {
Node initList1 = getLinkedList(36981);
Node initList2 = getLinkedList(689130);
printList(initList1);
printList(initList2);
printList(merge2Linkedlist(initList1,initList2));
}
//从头到尾打印单链表
public static void printList(Node head){
while(head!=null){
System.out.print(head.value+">>");
head = head.next;
}
System.out.println("null");
}
//数字转链表方法
//根据数字生成链表
public static Node getLinkedList(int num){
String s = num+"";
Node linkedList = null;
for(int i= 0;i<s.length();i++){
try{
Node node = new Node(Integer.parseInt(s.substring(i, i+1)));
node.next = linkedList;
linkedList = node;
}catch (NumberFormatException e){
}
}
return linkedList;
}
这里写代码片
//求两个链表的和
public static Node merge2Linkedlist(Node head1,Node head2){
if(head1==null){
return head2;
}else if(head2==null){
return head1;
}
Node temp1 = head1;
Node temp2 = head2;
Node head = null;//指向头
Node tail = null;//指向尾巴
int plusNum = 0;
int nodeValue = 0;
boolean firstIn = true;
while(temp1!=null||temp2!=null){
if(temp1!=null&&temp2!=null){
nodeValue = (temp1.value+temp2.value)%10+plusNum;
if(nodeValue==10){
nodeValue = 0;
}
plusNum = (temp1.value+temp2.value)/10;
temp1 = temp1.next;
temp2 = temp2.next;
}else{
if(temp1!=null){
if(firstIn){
nodeValue = temp1.value + plusNum;
firstIn = false;
}else{
nodeValue = temp1.value;
}
temp1 = temp1.next;
}else{
if(firstIn){
nodeValue = temp2.value + plusNum;
firstIn = false;
}else{
nodeValue = temp2.value;
}
temp2 = temp2.next;
}
}
Node node = new Node(nodeValue);
if(tail!=null){
tail.next = node;
tail = node;
}else{
tail = node;
head = node;
}
}
return head;
}
}