Jamie Jamier
Jamie Jamier

Reputation: 539

Comparing two linkedlist

I am new to programming.

I know there is a lot of better and nicer approach than mine to compare two linked-list. But, as I am new I would like to fix my code and get a sense of where I make the mistake.

What I am trying to do is loop through both of the linkedlist and compare each node at the same time.

Compare two linked lists A and B => Return 1 if they are identical and 0 if they are not.

I would genuinely appreciate your help in advance.

int CompareLists(Node headA, Node headB) {

    int i = 0;
    int j = 0;


    Node tmpA = headA;
    Node tmpB = headB;

    if(tmpB.next != null && tmpA.next == null) return 0;

    while(tmpA.next != null) {

        if(tmpB.next == null) return 0;

        while(tmpB.next != null) {

            if (i == j) {

                if (tmpA.data != tmpB.data) return 0;

            } else {
                break;
            }
            tmpB = tmpB.next;

            j++;



        }   

        i++;

        tmpA = tmpA.next;

    }

    if(tmpA.data != tmpB.data) return 0;
    else return 1;

}

Upvotes: 0

Views: 132

Answers (2)

Matt Timmermans
Matt Timmermans

Reputation: 59184

It gets better with practice

int CompareLists(Node a, Node b) {
    while(a!=null && b!=null && a.data == b.data) {
        a=a.next;
        b=b.next;
    }
    return (a==null && b==null ? 1: 0);
}

Upvotes: 3

kabanus
kabanus

Reputation: 25895

Here is a cleaned up version of your code. Your general idea was good, but you did add some complications.

  1. The two indices were unnecessary as you always keep your lists aligned (when B goes forward, you break if everything is OK and then A also goes forward). Which brings me to:
  2. You did not need an inner while and break, just an if to check the current node
  3. The one thing you did forget though - when tmpA.next is NULL you have not compared the current data of A and B - so you need to do one last check after the loop.

Here is a cleaned version:

int CompareLists(Node headA, Node headB) {    
    Node tmpA = headA;
    Node tmpB = headB;

    if(tmpB.next != null && tmpA.next == null) return 0;

    while(tmpA.next != null) {    
        if(tmpB.next == null || tmpA.data != tmpB.data) return 0;

        tmpB = tmpB.next;
        tmpA = tmpA.next;  
    }

    //Added:
    if(tmpB.next != null || tmpA.data != tmpB.data)  return 0;
    return 1;
}

Of course, you don't have to work on next all the time. You can just test for tmpA/tmpB == null etc., to save some more space - I'll leave it for your consideration.

The final nit-pick, as pointed out by @vatbub in the comments, try and use the most appropriate types - returning a Boolean is what you actually want here.

Upvotes: 3

Related Questions