Wednesday, December 28, 2011

Pending


3 comments:

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

    void print(struct node *head)
    {
    struct node *temp;
    temp = head;
    while(head != NULL)
    {
    printf("data : %d\n", head->data);
    head = head->next;
    }
    }

    void removeDup(struct node **head, int data)
    {
    struct node *first, *sec;
    first = *head;
    sec = *head;
    while(first != NULL)
    {
    // Check if the node data matches with given data
    if(first->data == data)
    {
    // if it matches with head of the linklist
    if(first == *head)
    {
    // Updated the head of the linklist
    *head = first->next;
    free(first);
    // Update first and second pointers
    first = *head;
    sec = *head;
    }
    else
    { // if it is not the head of the list
    // remove the node
    sec->next = first->next;
    // free its resource.
    free(first);
    // Update the first pointer
    first = sec->next;
    }
    }
    else
    {
    // Update second pointer with first
    // first pointer points to the next element
    sec = first;
    first = first->next;
    }
    }
    }

    void push(struct node **head, int data)
    {
    struct node *temp = (struct node *)malloc(sizeof(struct node));
    temp->data = data;
    temp->next = *head;
    // push the new node to the head
    *head = temp;
    }

    main()
    {
    struct node *head = NULL;
    push(&head, 5);
    push(&head, 6);
    push(&head, 1);
    push(&head, 3);
    push(&head, 5);
    push(&head, 5);
    push(&head, 7);
    push(&head, 8);
    push(&head, 5);
    removeDup(&head, 5);
    print(head);
    }

    ReplyDelete
  2. A nice explanation of removing duplicates from a list is at

    http://www.ritambhara.in/remove-duplicates-from-a-linked-list/

    ReplyDelete