adding two linked lists efficiently in C

前端 未结 2 1223
天命终不由人
天命终不由人 2021-02-09 09:21

I have two linked lists representing the digits of decimal numbers in order from most- to least-significant. for eg 4->7->9->6 and 5->7 The

2条回答
  •  生来不讨喜
    2021-02-09 10:04

    This is how I would go about solving this:

    Step 1: Make a pass on both linked lists, find lengths

    say len(L1) = m and len(L2) = n

    Step 2: Find difference of lengths

    if ( m > n )
        d = m - n
    else if ( n > m )
        d = n - m
    else
        d = 0
    

    Step 3: Move a temporary pointer d ahead of the larger list

    Step 4: Now we have two linked lists to add whose lengths are same, so add them recursively, maintaining a carry.

    Step 5: ( Note: if ( d == 0 ) don't perform this step )

    After step 4, we've got partial output list, and now we have to put remaining of the larger list at the beginning of output list.

    if ( d > 0 )
        -Travel larger list till d positions recursively
        -Append sum = value_at_end + carry (update carry if sum >= 10) to output list at beginning
        -Repeat until difference is consumed
    

    Note: I'm solving the problem as its put before me, not by suggesting the change in underlying data structure.

    Time complexity:

    1. Making single passes on both the lists to find their lengths: O(m+n)
    2. Summing two linked lists of equal size (m - d and n) recursively: O(n), assuming m > n
    3. Appending remaining of larger list to output list: O(d)

    Total: O( (m+n) + (n) + (d) ) OR O(m+n)

    Space complexity:

    1. step 2 of time complexity: O(n), run time stack space
    2. step 3 of time complexity: O(d), run time stack space

    Total: O(n + d) OR O(n)

提交回复
热议问题