笔试碰到一题,有两个数,如123456789和1234567,将每个数字放入链表,然后不修改链表的情况下求和。
说实话,被pass了,笔试时整个人状态都是懵的,本来算法不强,结果状态很丧,结束后整理了一下,才发现题意原来是这意思。
package com.example.test;
import java.util.LinkedList;
/**
* @author soft_hzhk
*/
public class SinNode {
private int value;
public SinNode next;
public SinNode(int value){
this.value=value;
}
public int getValue() {
return value;
}
private static SinNode sumResult(SinNode sinNode1,SinNode sinNode2){
LinkedList<Integer> list1=new LinkedList<>();
LinkedList<Integer> list2=new LinkedList<>();
while (sinNode1!=null){
list1.push(sinNode1.getValue());
sinNode1=sinNode1.next;
}
while (sinNode2!=null){
list2.push(sinNode2.getValue());
sinNode2=sinNode2.next;
}
SinNode sinNode=new SinNode(0);
int mode=0;
while (!list1.isEmpty()||!list2.isEmpty()||mode!=0){
int v1 = list1.isEmpty() ? 0 : list1.pop();
int v2 = list2.isEmpty() ? 0 : list2.pop();
int sum = v1 + v2 + mode;
SinNode node = new SinNode(sum % 10);
node.next = sinNode.next;
sinNode.next = node;
mode = sum / 10;
}
return sinNode.next;
}
private static void printNode(SinNode sinNode){
if (sinNode != null) {
System.out.println("----"+sinNode.getValue());
printNode(sinNode.next);
}
}
public static void main(String[] args){
SinNode s1,s2,event1,event2;
int length1=10;
int length2=8;
event1=s1=new SinNode(1);
event2=s2=new SinNode(1);
for (int i = 2; i < length1; i++) {
SinNode sinNode=new SinNode(i);
s1.next=sinNode;
s1=s1.next;
}
for (int i = 2; i < length2; i++) {
SinNode sinNode=new SinNode(i);
s2.next=sinNode;
s2=s2.next;
}
SinNode reorderNodeList = sumResult(event1,event2);
printNode(reorderNodeList);
}
}