LeetCode 題解與知識點 2. 兩數相加 Add-Two-Numbers

題目連接

2. Add-Two-Numbers 難度:$\color{#00965e}{medium}$node

知識點

1.數據結構單鏈表

數據結構基礎,此處不贅述segmentfault

2.鏈表尾插法

C 單鏈表頭插法/尾插法/刪除指定值結點數據結構

解法

簡單累加

  • 留心進位
  • 用head記錄頭結點,head->next即題解須要的頭結點
複雜度分析
  • 時間複雜度:O(max(m,n)),其中 m,nm,n 爲兩個鏈表的長度。咱們要遍歷兩個鏈表的所有位置,而處理每一個位置只須要 O(1)O(1) 的時間。
  • 空間複雜度:O(max(m,n)),答案鏈表的長度最多爲較長鏈表的長度 +1+1。

如下爲PHP語言實現~~~~this

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val = 0, $next = null) {
 *         $this->val = $val;
 *         $this->next = $next;
 *     }
 * }
 */
class Solution {
    /**
     * @param ListNode $l1
     * @param ListNode $l2
     * @return ListNode
     */
    function addTwoNumbers($l1, $l2) {
        $carry      = 0;
        $tmp_int    = 0;
        $head       = new ListNode();
        $end        = new ListNode();
        $end        = $head;
        //$head     = $end;//與上面的寫法實際上是同樣的,這裏的head是保存了頭結點
        while($l1 !=NULL || $l2!=NULL || $carry > 0){
            if ($l1 != NULL){
                $tmp_int += $l1->val;
                $l1       = $l1->next;
            }
            if ($l2 != NULL){
                $tmp_int += $l2->val;
                $l2       = $l2->next;
            }
            $tmp_int += $carry;
            $node     = new ListNode();
            $node->val= $tmp_int%10;
            $carry    = floor($tmp_int/10);
            $tmp_int  = 0;
            $end->next= $node;                             
            $end = $node;
        }
        return $head->next;
    }
}
相關文章
相關標籤/搜索