0

I have been practicing DS using C and feel sorry for my unreadable code.

i tried to implement linked list using C and i am beginner to learn data structures

Please help me why this is running slow.

#include <stdio.h>
#include <stdlib.h>
typedef struct node{
    int data;
    struct node* link;
}NODE;
int main(void){
    NODE* A;
    A = NULL;
    NODE* temp = (NODE*)malloc(sizeof(NODE));
    temp->data = 2;
    temp->link = NULL;
    A = temp;
    temp = (NODE*)malloc(sizeof(NODE));
    temp->data = 3;
    temp->link = NULL;
    A->link = temp;
    temp = (NODE*)malloc(sizeof(NODE));
    temp->data = 5;
    temp->link = NULL;
    NODE* temp1 = A;
    while(temp1->link != NULL){
        printf("%d\n",temp1->data);
        temp1 = temp1->link;
        printf("%d\n",temp1->data);
        
    }
    temp1->link = temp;
    temp1 = temp1->link;
    printf("%d\n",temp1->data);
    temp1 = A;
    printf("%d\n",temp1->data);
    printf("after inserting 100 in to the second\n");
    int count = 1;
    NODE* new = (NODE*)malloc(sizeof(NODE));
    new->data = 100;
    new->link = NULL;
    NODE* before = (NODE*)malloc(sizeof(NODE));
    NODE* after = (NODE*)malloc(sizeof(NODE));
    while(temp1->link != NULL){
        if(count == 2){
            new->link = temp1;
            break;
        }
        if(count == 1){
            before = temp1->link;
            temp1->link = new;
            temp1 = before;
            count++;
            continue;
        }
        temp1 = temp1->link;
        count++;
    }
    temp1 = A;
     while(temp1->link != NULL){
        printf("%d\n",temp1->data);
        temp1 = temp1->link;
    }
    printf("%d\n",temp1->data);
}
Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61

2 Answers2

0

So as per @Barmar's remark, I see that you are allocating some memory but never freeing that memory which is a big NO-NO. Always make sure you are freeing any dynamically allocated memory.

Regarding your question, try to use gettimeofday() in order to find how long it is taking your code to execute. I assume it is very quick but maybe there is an issue with your computer and is giving the illusion that it is slow.

    #include <sys/time.h>

...
int main(..)
{
struct timeval tv_start, tv_end;
gettime ofday(&tv_start, NULL);

....
....

gettimeofday(&tv_end, NULL);
double run_time = ( double )( tv_end.tv_usec - tv_start.tv_usec ) / 1000000 + ( double )( tv_end.tv_sec - tv_start.tv_sec);

printf("Total runtime %f \n", run_time);

JJ Adams
  • 481
  • 4
  • 17
0

Your code ran 10,000 times in 25 seconds on my ubuntu virtual box (On Windows 10). Do you expect faster than that for this particular code, or your actual use-case is much larger?

#!/bin/bash

ts=$(date +%s%N)

for i in {1..10000}
do
   ./a.out  >/dev/null
done

echo "Elapsed"
echo $((($(date +%s%N) - $ts)/1000000000))

Elapsed 25

FEldin
  • 131
  • 7