啥意思:计算加法:比如:9->9->9->9 + 1->9->7 = 0->9->7->0->1
精髓:就是抠好链表的长度,找出谁是长链表,因为长链表肯定得留到最后
/**
* 两个链表相加
*/
public class Code06 {
public static class Node<V> {
public V value;
public Node<V> last;
public Node<V> next;
public Node() {
}
public Node(V v) {
value = v;
last = null;
next = null;
}
}
public static void print(Node head){
while (head != null){
System.out.print(head.value+" ");
head = head.next;
}
}
public static void main(String[] args) {
Node node1 = new Node(9);
Node node2 = new Node(9);
Node node3 = new Node(9);
Node node4 = new Node(9);
Node node5 = new Node(1);
Node node6 = new Node(9);
Node node7 = new Node(7);
node1.next=node2;
node2.next=node3;
node3.next = node4;
node5.next = node6;
node6.next = node7;
Node ret = addLinkList(node1,node5);
print(ret);
}
private static int length(Node node){
int length = 0;
while (node != null){
length++;
node = node.next;
}
return length;
}
private static Node<Integer> addLinkList(Node<Integer> node1, Node<Integer> node2) {
int len1 = length(node1);
int len2 = length(node2);
Node<Integer> l = len1 >= len2 ? node1 : node2;
Node<Integer> s = l==node1 ? node2 : node1;
Node<Integer> curL = l;
Node<Integer> curS = s;
// 进位信息
int carrayNum = 0;
Node<Integer> cur = curL;
while (curS != null){
int num = curL.value+curS.value+carrayNum;
int yu = num%10;
int shang = num/10;
curL.value = yu;
carrayNum = shang;
cur = curL;
curL = curL.next;
curS = curS.next;
}
while (curL != null){
int num = curL.value+carrayNum;
int yu = num%10;
int shang = num/10;
curL.value = yu;
carrayNum = shang;
cur = curL;
curL = curL.next;
}
if(carrayNum>0){
Node<Integer> end = new Node<>(carrayNum);
cur.next = end;
}
return l;
}
}
这篇博客详细介绍了如何实现两个链表相加的算法。通过计算每个节点的值和进位,逐步遍历并更新链表,确保较短的链表在前,最后处理可能的进位。该算法涉及链表操作和进位逻辑,是数据结构和算法的经典问题。
288

被折叠的 条评论
为什么被折叠?



