0

I have to print out every unique integer in a linked list, it turned out the it's not printing anything.I tried using continue and remove the else but by doing that I only get the first unique item in the linked list. My question is that does continue end the loop or just skip the current iteration? If it only skips the current one, say i have a linked list that looks like 1->5, why am I only getting 1 printed here? Thanks in advance.

 struct node {
    int data; 
    struct node* next; 
 }


void printList(struct node *head)  // print out unique items of the list
{

    struct node *ptr = head;
    struct node *prev = NULL;

    while(ptr != NULL)
    {

        if(prev->data == ptr->data)
        {
            prev = ptr;
            ptr = ptr->next;

        }else{
        printf("%d", ptr->data);
        prev = ptr;
        ptr = ptr->next;

        }

    }
}
6
  • What does struct node look like? Commented Feb 20, 2019 at 20:56
  • break breaks out of the loop, continue ... continues the loop. That's very basic C knowledge covered in every C text book. Commented Feb 20, 2019 at 20:56
  • 2
    Are you getting any errors when you run it? It looks like you should to me, since you'll be dereferencing a null pointer the first time you evaluate prev->data. Commented Feb 20, 2019 at 20:56
  • Aside: the code could be much simplifed by a slight reordering and the removal of the duplication of prev = ptr; ptr = ptr->next; which are needed whether or not there was a match found. Commented Feb 20, 2019 at 20:58
  • struct node { int data; struct node* next; }; here's the struct node Commented Feb 20, 2019 at 21:00

1 Answer 1

1

The code as written generates a segmentation fault because you're referencing a NULL pointer. In this line:

if(prev->data == ptr->data)

Since prev is NULL to start, prev->data will dereference the NULL pointer and crash the program. That doesn't explain why you saw it not printing the last element, but the code as written is definitely broken.

Try this:

void printList(struct node *head)  // print out unique items of the list
{

    struct node *ptr = head;
    struct node *prev = NULL;

    while (ptr != NULL)
    {
        // Check if prev is NULL, and if not, that prev->data and ptr->data
        // don't match.
        if (! prev || ptr->data != prev->data)
        {
            printf("%d\n", ptr->data);
        }

        prev = ptr;
        ptr = ptr->next;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! It worked. Could you explain what does !prev stand for?
!prev is a short way of saying prev == NULL. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.