Linked List and array

Viewed 600

I know StackOverflow isn't writing the question and getting the answer site but here is my problem from leetcode.

l1 = input()
l2 = input()
def f(x): #Gives reversed of linkedlist ex. [2, 4, 3] return 342
    a, u = 0, 0
    for ele in x:
        if ele.isnumeric():
            a += int(ele)*(10**u)
            u += 1
    return a
l = list(int(i) for i in str(f(l1) + f(l2)))
print(list(reversed(l)))

This question is leet code problem so here I have solved the problem but this is something different they do not want spaces between the number after comma.

  • Input: [2,4,3] [5,6,4]

  • My output: [7, 0, 8]

  • Expected output: [7,0,8]

However, I also tried

k = str(f(l1) + f(l2))
print("[" + ",".join(str(k)[::-1]) + "]")
3 Answers

You aren't supposed to use input() and print() on leetcode

When you start a problem they give you a function you have to fill and return the result.

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        #put your code here
        return the_result

This problem is supposed to use a linked list with nodes defined as

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

this is what should be the input of the addTwoNumbers() method you are supposed to code.

But somehow by using input() you are bypassing this and grabbing the raw list.

Also, prints(stdout) are not what is being evaluated by the leetcode system, they look for the output of addTwoNumbers() which in this case is blank.

That is just the default representation of a list, it has a space after each comma

x = [1, 2, 3]
print(x)                        # [1, 2, 3]  type is list
print(str(x).replace(" ", ""))  # [1,2,3]    type is str

Here is the complete solution;

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def __init__(self):
        self.head = None

    def rev(self, ls):
        res = []

        self.head = ls
        while self.head:
            res.append(str(self.head.val))
            self.head = self.head.next

        return list(reversed(res))
    
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        res1 = int(''.join(self.rev(l1)))
        res2 = int(''.join(self.rev(l2)))
        
        res3 = str(res1 + res2)
        resls = list(reversed([i for i in res3]))
        
        self.head = ListNode(resls[0], None)
        finalres = self.head
        for i in range(1, len(resls)):
            lsn = ListNode(resls[i], None)
            finalres.next = lsn
            finalres = finalres.next
            
        return self.head 
        
**Explanation**:

I will asume that you know the basics of linked lists i.e, what are they (in case you have confusion please comment).

So in the Solution class, i simply defined a self.head attribute inside its __init__ method which i am going to use to keep track of elements in a linked list. It is initially set to None as right there we don't have any data there.

Then i defined a rev method to reverse the given linked list.

Inside the rev, i created an empty list res to store the data from the linked lists provided.

Rev also takes a linked list as an argument as i will take the data from it and append it to the res list

So i put self.head equal to that linked list ls provided when we call the method.

Then i simply ran a while loop until self.head is defined (i.e, until it is not None which means there is still data).

After every iteration, i kept changing self.head to self.head.next to move forward in the linked list and grab the data from every node of that linked list and append that to res list.

At the end i simply returned the reversed res.

Then i defined another method, addTwoNumbers which takes two linked lists and returns there sum as per the requirement.

First of all i need those two linked lists to be in integer form and reversed ( as per condition). So i used the rev method to reverse them, join method (inbuilt method in python to join a list of strings) to convert the list to string and then int method to convert the string to int.

I did the same with both of the linked lists and stored them in res1 and res2 respectively.

Then i took their sum (res3) and converted it to string as we cannot iterate over an integer .

Then i converted the res3 to a reversed list .

Now the last step, return the whole thing as a listnode.

So i simply created an instance of ListNode;

self.head = ListNode(resls[0], None)

This will create an instance of ListNode with data as first element of resls and next as none.

Then i stored it inside another variable to refrence to the same instance and don't change it.

Then ran a far loop on the remaining elements and kept adding data and next.

Hope you understood. Thanks.

Related