When adding lists, why not provide lists as the parameters and return a list

  • 0

    The question says adding two lists and the result is also a list, so why does the addTwoNumbers() method take 2 nodes as parameters instead of linkedlists. My code is as follows:
    public LinkedList addLists(LinkedList list1, LinkedList list2) {
    LinkedList resultList = new LinkedList();
    Node ptr1 = list1.first;
    Node ptr2 = list2.first;
    Node current = resultList.first;
    int carry = 0;
    while(ptr1 != null || ptr2!=null ){
    int dataPtr1 = (ptr1!=null)?ptr1.getData():0;
    int dataPtr2 = (ptr2!=null)?ptr2.getData():0;

    			int sum = dataPtr1 + dataPtr2 +carry;
    			carry = sum/10;
    			if(ptr1!=null){ptr1 = ptr1.getNext();}
    			if(ptr2!=null){ptr2 = ptr2.getNext();}
    		if(carry >0){
                   return resultList;


    insertLast() is a method where the every time when a new node is created, it can be inserted into the linkedlist. Here is the code for insertLast():
    '''public void insertLast(int data){
    Node newNode = new Node(data);
    first = newNode;
    last = newNode;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.