1. 程式人生 > >2.5給定兩個用鏈表表示的整數,每個結點包含一個數位。這些數位是反向存放的,也就是個位排在鏈表首部。編寫函數對這兩個整數求和,並用鏈表形式返回結果。

2.5給定兩個用鏈表表示的整數,每個結點包含一個數位。這些數位是反向存放的,也就是個位排在鏈表首部。編寫函數對這兩個整數求和,並用鏈表形式返回結果。

直接 logs next 末尾 做的 nbsp before != 結果

其實仔細想想是挺簡單的,我們要做的只是記得進位。

LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2, int carry)
//LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2, int carry = 0)
{
    if (l1 == null && l2 == null $$ carry == 0)
    {
        return null;
    }
    
    LinkedListNode result = new
LinkedListNode(); int value = carry; if (l1 != null) { value += l1.data; } if (l2 != null) { value += l2.data; } result.data = value%10; LinkedListNode more = addLists(l1 == null? null : l1.next, l2 == null? null : l2.next, value >= 10? 1 :0); result.setNext(more); }

進階:假設是正向存放的。

坑:1,註意雙方長度,雙方是末尾對齊的,不足的地方需要用0補足。

//2.5b進階:假設這些數位是正向存放的
public class PartialSum
{
    public LinkedListNode sum = null;
    public int carry = 0;
}

LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2)
{
    int len1 = length(l1);
    int len2 = length(l2);
    
    //用零填充較短的鏈表
    if
(len1 < len2) { l1 = padList(l1, len2 - len1); } else { l2 = padList(l2, len1 - len2); } //對兩個鏈表求和 PartialSum sum = addListsHelper(l1, l2); //如有進位,則插入鏈表首部,否則,直接返回整個鏈表 if (sum.carry == 0) { return sum.sum; } else { LinkedListNode result = insertBefore(sum.sum, sum.carry); return result; } } PartialSum addListsHelper(LinkedListNode l1, LinkedListNode l2) { if (l1 == null && l2 == null) { PartialSum sum = new PartialSum(); return sum; } //先遞歸為較小數字求和 PartialSum sum = addListsHelper(l1.next, l2.next); //將進位和當前數據相加 int val = sum.carry + l1.data + l2.data; //插入當前數字的求和結果 LinkedListNode full_result = insertBefore(sum.sum, val % 10); //返回求和結果與進位值 sum.sum = full_result; sum.carry = val/10; return sum; } //用零填充鏈表 LinkedListNode padList(LinkedListNode l,int padding) { LinkedListNode head = l; for (int i = 0; i < padding; i++) { LinkedListNode n = new LinkedListNode(0, null, null); head.prev = n; n.next = head; head = n; } return head; } //輔助函數,將結點插入鏈表首部 LinkedListNode insertBefore(LinkedListNode list, int data) { LinkedListNode node = new LinkedListNode(data, null, null); if (list != null) { list.prev = node; node.next = list; } return node; }

2.5給定兩個用鏈表表示的整數,每個結點包含一個數位。這些數位是反向存放的,也就是個位排在鏈表首部。編寫函數對這兩個整數求和,並用鏈表形式返回結果。