Scheduled Maintenance: We are aware of an issue with Google, AOL, and Yahoo services as email providers which are blocking new registrations. We are trying to fix the issue and we have several internal and external support tickets in process to resolve the issue. Please see: viewtopic.php?t=158230

 

 

 

Duplicated first insertion

Programming languages, Coding, Executables, Package Creation, and Scripting.
Post Reply
Message
Author
reiko
Posts: 100
Joined: 2015-09-02 22:40

Duplicated first insertion

#1 Post by reiko »

ok in this code the program is running but there is a problem the first insertion of data to the linked list
i get duplicated output on the print this is the code im running codeblocks 13.12 :
p.s
i also like to learn the logic why this is happen. tnx in advance

Code: Select all

#include <stdio.h>
#include <stdlib.h>

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

struct node* head = NULL;

void Insert(int c)
{
if(head == NULL) {
    struct node* temp = malloc(sizeof(struct node));
    temp -> data = c;
    temp -> next = NULL;
    head = temp;
}

struct node* temp = malloc(sizeof(struct node));
temp -> data = c;
temp -> next = NULL;
struct node* temp1 = head;

    while (temp1->next != NULL) {
        temp1 = temp1->next;

}
temp1 -> next = temp;
    }

void print() {

    struct node* temp = head;
    printf("list is: \n");
    while (temp != NULL) {

        printf( "%d ,",temp->data);
        temp = temp->next;
    }
}


int main () {

printf("How Many Numbers?\n");
int a ,b ,c;
scanf("%d" , &b);
for(a = 0;a<b;a++) {
    printf("Enter the numbers \n");
    scanf("%d",&c);
    Insert(c);
    print();
}
return 0;
}

tomazzi
Posts: 730
Joined: 2013-08-02 21:33

Re: Duplicated first insertion

#2 Post by tomazzi »

Hi,
It would take a long time to point out and explain all the bugs in this piece of code, so here's a very short list:

1. The Insert() function is not inserting the elements - it is Append()-ing them -> that's quite a big difference.
2. The first element is indeed doubled, because there's missing return statement in the header initialization:

Code: Select all

if(head == NULL) {
    struct node* temp = malloc(sizeof(struct node));
    temp -> data = c;
    temp -> next = NULL;
    head = temp;
    return; /* !HERE! */
}
3. In the scheme which is used in Your code, the Header should be simply a pointer to the first element and the above fragment of code is simply redundant.

Regards.
Odi profanum vulgus

Post Reply