Hey.
This is the code of a list implementation and some function to remove duplicates in it.
I have small question about the two final lines in push function:
First, we define the next element of the new node as the former head - using de-reference.
And after that, we define the head to be equal to the address of the new node.
For me, it looks like a buggy circle somehow...
I see it so:
The next element of the new node is pointing to the former (about to be) head.
Now, this former head is being equal to new node.
So it seems like the new node's next at first points to the former head, and then this next is pointing to the new node (as we define *head to be equal to new node).
Eventually, I see it as if new node's next points to new node, instead of to the former head.
What am I missing here?
Thank you all!
Code:#include <stdlib.h> #include <stdio.h> typedef struct Node { int data; struct Node* next; } Node; void printList(Node *head) { Node* p = head; while (p !=NULL) { printf("%d ", p->data); p = p->next; } printf("\n"); } void push(Node** head, int new_data) { Node* new_node = (Node*) malloc(sizeof(Node)); new_node->data = new_data; new_node->next = *head; *head = new_node; } void deleteList(Node** head) { Node* p = *head; while (p !=NULL) { Node *next = p->next; free(p); p = next; } *head = NULL; } void removeDuplicates(Node *head) { Node *ptr1, *ptr2; ptr1 = head; while (ptr1 != NULL ) { ptr2 = ptr1; while (ptr2->next != NULL) { // iterate the list from ptr2 if (ptr1->data == ptr2->next->data) { // need to delete Node* tmp = ptr2->next; ptr2->next = ptr2->next->next; free(tmp); } else { ptr2 = ptr2->next; } } ptr1 = ptr1->next; // move to next node } } void myListTest() { Node* phead = NULL; for(int i=0; i<10; i++) { push(&phead, i); push(&phead, 10-i); } printList(phead); removeDuplicates(phead); printList(phead); deleteList(&phead); } int main() { myListTest(); return 0; }