What is the fastest way to implement a list and queue in c? The Next CEO of Stack OverflowRelative performance of std::vector vs. std::list vs. std::slist?What is the difference between #include <filename> and #include “filename”?What is tail recursion?What is the best algorithm for an overridden System.Object.GetHashCode?What is a plain English explanation of “Big O” notation?What is the effect of extern “C” in C++?Using malloc in C to allocate space for a typedef'd typeWhat does the C ??!??! operator do?What is “:-!!” in C code?What is the optimal algorithm for the game 2048?B-tree in pseudocode

Vector calculus integration identity problem

Why is information "lost" when it got into a black hole?

Cannot shrink btrfs filesystem although there is still data and metadata space left : ERROR: unable to resize '/home': No space left on device

Easy to read palindrome checker

Is it ok to trim down a tube patch?

Is a distribution that is normal, but highly skewed, considered Gaussian?

Small nick on power cord from an electric alarm clock, and copper wiring exposed but intact

What day is it again?

Can this note be analyzed as a non-chord tone?

Can Sneak Attack be used when hitting with an improvised weapon?

What steps are necessary to read a Modern SSD in Medieval Europe?

Where do students learn to solve polynomial equations these days?

Is fine stranded wire ok for main supply line?

Why do we say 'Un seul M' and not 'Une seule M' even though M is a "consonne"

Is dried pee considered dirt?

What happened in Rome, when the western empire "fell"?

Is it professional to write unrelated content in an almost-empty email?

Physiological effects of huge anime eyes

How to Implement Deterministic Encryption Safely in .NET

Strange use of "whether ... than ..." in official text

Is there a difference between "Fahrstuhl" and "Aufzug"?

Are the names of these months realistic?

Which one is the true statement?

Getting Stale Gas Out of a Gas Tank w/out Dropping the Tank



What is the fastest way to implement a list and queue in c?



The Next CEO of Stack OverflowRelative performance of std::vector vs. std::list vs. std::slist?What is the difference between #include <filename> and #include “filename”?What is tail recursion?What is the best algorithm for an overridden System.Object.GetHashCode?What is a plain English explanation of “Big O” notation?What is the effect of extern “C” in C++?Using malloc in C to allocate space for a typedef'd typeWhat does the C ??!??! operator do?What is “:-!!” in C code?What is the optimal algorithm for the game 2048?B-tree in pseudocode










1















Which one stack and queue realization will be faster and more optimal and why? Based on array (dynamic or static) or list?



For example, I have these ways:



Dynamic array based:



typedef struct Stack 
char* values;
int avl_el;
int now_el;
int top;
Stack;

void push(Stack* stack, char data)
if (stack->now_el >= stack->avl_el)
stack->avl_el += INCR;
stack->values = (char*)malloc(stack->avl_el * sizeof(char));

if (stack->top == -1)
stack->top++;
stack->values[stack->top] = data;
stack->now_el++;
else
stack->top++;
stack->values[stack->top] = data;
stack->now_el++;



char pop(Stack* stack)
char tmp = stack->values[stack->top];
stack->values[stack->top] = 0;
stack->top--;
stack->now_el--;
return tmp;



List based:



typedef struct Node 
char data; // in this case we save char symb
struct Node *next;
Node;

typedef struct Stack
struct Node* topElem;
Stack;

void push(Stack* stack, char data)
Node* tmp = (Node*)malloc(1 * sizeof(Node));
if(!tmp)
printf("Can't push!n");
return;

tmp->data = data;
tmp->next = stack->topElem;
stack->topElem = tmp; // making new top element


char pop(Stack* stack)
Node* tmp = stack->topElem;
char del_data = stack->topElem->data;
stack->topElem = stack->topElem->next;
free(tmp);
return del_data;



Will be any different with stack based on dynamic and stack based on static arrays?










share|improve this question

















  • 6





    Run benchmarks and see for yourself?

    – John Coleman
    Mar 21 at 19:07






  • 2





    Considering that your first implementation is wrong (you throw away all elements when increasing the size) and leaks memory I think you should first worry about fixing that before worrying about performance

    – UnholySheep
    Mar 21 at 19:09












  • @JohnColeman, I need an answer акщь the part of the algorithm, not just the running time. How to justify this theoretically?

    – P. Nikita
    Mar 21 at 19:10











  • @UnholySheep, Yes, I understand it and that's hastily realization just for example and to express more clearly my question. Also, with my test, it works normally.

    – P. Nikita
    Mar 21 at 19:13
















1















Which one stack and queue realization will be faster and more optimal and why? Based on array (dynamic or static) or list?



For example, I have these ways:



Dynamic array based:



typedef struct Stack 
char* values;
int avl_el;
int now_el;
int top;
Stack;

void push(Stack* stack, char data)
if (stack->now_el >= stack->avl_el)
stack->avl_el += INCR;
stack->values = (char*)malloc(stack->avl_el * sizeof(char));

if (stack->top == -1)
stack->top++;
stack->values[stack->top] = data;
stack->now_el++;
else
stack->top++;
stack->values[stack->top] = data;
stack->now_el++;



char pop(Stack* stack)
char tmp = stack->values[stack->top];
stack->values[stack->top] = 0;
stack->top--;
stack->now_el--;
return tmp;



List based:



typedef struct Node 
char data; // in this case we save char symb
struct Node *next;
Node;

typedef struct Stack
struct Node* topElem;
Stack;

void push(Stack* stack, char data)
Node* tmp = (Node*)malloc(1 * sizeof(Node));
if(!tmp)
printf("Can't push!n");
return;

tmp->data = data;
tmp->next = stack->topElem;
stack->topElem = tmp; // making new top element


char pop(Stack* stack)
Node* tmp = stack->topElem;
char del_data = stack->topElem->data;
stack->topElem = stack->topElem->next;
free(tmp);
return del_data;



Will be any different with stack based on dynamic and stack based on static arrays?










share|improve this question

















  • 6





    Run benchmarks and see for yourself?

    – John Coleman
    Mar 21 at 19:07






  • 2





    Considering that your first implementation is wrong (you throw away all elements when increasing the size) and leaks memory I think you should first worry about fixing that before worrying about performance

    – UnholySheep
    Mar 21 at 19:09












  • @JohnColeman, I need an answer акщь the part of the algorithm, not just the running time. How to justify this theoretically?

    – P. Nikita
    Mar 21 at 19:10











  • @UnholySheep, Yes, I understand it and that's hastily realization just for example and to express more clearly my question. Also, with my test, it works normally.

    – P. Nikita
    Mar 21 at 19:13














1












1








1








Which one stack and queue realization will be faster and more optimal and why? Based on array (dynamic or static) or list?



For example, I have these ways:



Dynamic array based:



typedef struct Stack 
char* values;
int avl_el;
int now_el;
int top;
Stack;

void push(Stack* stack, char data)
if (stack->now_el >= stack->avl_el)
stack->avl_el += INCR;
stack->values = (char*)malloc(stack->avl_el * sizeof(char));

if (stack->top == -1)
stack->top++;
stack->values[stack->top] = data;
stack->now_el++;
else
stack->top++;
stack->values[stack->top] = data;
stack->now_el++;



char pop(Stack* stack)
char tmp = stack->values[stack->top];
stack->values[stack->top] = 0;
stack->top--;
stack->now_el--;
return tmp;



List based:



typedef struct Node 
char data; // in this case we save char symb
struct Node *next;
Node;

typedef struct Stack
struct Node* topElem;
Stack;

void push(Stack* stack, char data)
Node* tmp = (Node*)malloc(1 * sizeof(Node));
if(!tmp)
printf("Can't push!n");
return;

tmp->data = data;
tmp->next = stack->topElem;
stack->topElem = tmp; // making new top element


char pop(Stack* stack)
Node* tmp = stack->topElem;
char del_data = stack->topElem->data;
stack->topElem = stack->topElem->next;
free(tmp);
return del_data;



Will be any different with stack based on dynamic and stack based on static arrays?










share|improve this question














Which one stack and queue realization will be faster and more optimal and why? Based on array (dynamic or static) or list?



For example, I have these ways:



Dynamic array based:



typedef struct Stack 
char* values;
int avl_el;
int now_el;
int top;
Stack;

void push(Stack* stack, char data)
if (stack->now_el >= stack->avl_el)
stack->avl_el += INCR;
stack->values = (char*)malloc(stack->avl_el * sizeof(char));

if (stack->top == -1)
stack->top++;
stack->values[stack->top] = data;
stack->now_el++;
else
stack->top++;
stack->values[stack->top] = data;
stack->now_el++;



char pop(Stack* stack)
char tmp = stack->values[stack->top];
stack->values[stack->top] = 0;
stack->top--;
stack->now_el--;
return tmp;



List based:



typedef struct Node 
char data; // in this case we save char symb
struct Node *next;
Node;

typedef struct Stack
struct Node* topElem;
Stack;

void push(Stack* stack, char data)
Node* tmp = (Node*)malloc(1 * sizeof(Node));
if(!tmp)
printf("Can't push!n");
return;

tmp->data = data;
tmp->next = stack->topElem;
stack->topElem = tmp; // making new top element


char pop(Stack* stack)
Node* tmp = stack->topElem;
char del_data = stack->topElem->data;
stack->topElem = stack->topElem->next;
free(tmp);
return del_data;



Will be any different with stack based on dynamic and stack based on static arrays?







c algorithm






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 21 at 19:05









P. NikitaP. Nikita

347




347







  • 6





    Run benchmarks and see for yourself?

    – John Coleman
    Mar 21 at 19:07






  • 2





    Considering that your first implementation is wrong (you throw away all elements when increasing the size) and leaks memory I think you should first worry about fixing that before worrying about performance

    – UnholySheep
    Mar 21 at 19:09












  • @JohnColeman, I need an answer акщь the part of the algorithm, not just the running time. How to justify this theoretically?

    – P. Nikita
    Mar 21 at 19:10











  • @UnholySheep, Yes, I understand it and that's hastily realization just for example and to express more clearly my question. Also, with my test, it works normally.

    – P. Nikita
    Mar 21 at 19:13













  • 6





    Run benchmarks and see for yourself?

    – John Coleman
    Mar 21 at 19:07






  • 2





    Considering that your first implementation is wrong (you throw away all elements when increasing the size) and leaks memory I think you should first worry about fixing that before worrying about performance

    – UnholySheep
    Mar 21 at 19:09












  • @JohnColeman, I need an answer акщь the part of the algorithm, not just the running time. How to justify this theoretically?

    – P. Nikita
    Mar 21 at 19:10











  • @UnholySheep, Yes, I understand it and that's hastily realization just for example and to express more clearly my question. Also, with my test, it works normally.

    – P. Nikita
    Mar 21 at 19:13








6




6





Run benchmarks and see for yourself?

– John Coleman
Mar 21 at 19:07





Run benchmarks and see for yourself?

– John Coleman
Mar 21 at 19:07




2




2





Considering that your first implementation is wrong (you throw away all elements when increasing the size) and leaks memory I think you should first worry about fixing that before worrying about performance

– UnholySheep
Mar 21 at 19:09






Considering that your first implementation is wrong (you throw away all elements when increasing the size) and leaks memory I think you should first worry about fixing that before worrying about performance

– UnholySheep
Mar 21 at 19:09














@JohnColeman, I need an answer акщь the part of the algorithm, not just the running time. How to justify this theoretically?

– P. Nikita
Mar 21 at 19:10





@JohnColeman, I need an answer акщь the part of the algorithm, not just the running time. How to justify this theoretically?

– P. Nikita
Mar 21 at 19:10













@UnholySheep, Yes, I understand it and that's hastily realization just for example and to express more clearly my question. Also, with my test, it works normally.

– P. Nikita
Mar 21 at 19:13






@UnholySheep, Yes, I understand it and that's hastily realization just for example and to express more clearly my question. Also, with my test, it works normally.

– P. Nikita
Mar 21 at 19:13













1 Answer
1






active

oldest

votes


















3














Assuming you fix your bugs, let's discuss the principles. The biggest performance bug is incrementing size with a constant INC. With this bug, the complexity for inserting n elements is O(n2). For better complexity, reallocate in multiples of 2 or 1.5, after the fix the complexity of inserting n elements becomes O(n), or amortized O(1) for a single insertion.



The two approaches have been tested extensively with C++: what is faster std:: vector (similar to your stack) or std::list (a doubly linked list). Here is a list of resources:




  • Bjarne Stroustrup, the creator of c++, compared lists and vectors.

  • stack overflow: Relative performance of std::vector vs. std::list vs. std::slist?

Lists are easier to implement, and have a better predictability (no resizing), but vectors are faster in the stack scenario on average, and more memory efficient.



Vectors (the stack in the question):



Size: No need to store pointers to the next element. So it's more efficient.



Speed: consecutive elements are near each other, resulting in better memory predictability, and higher cache efficiency.



lists:



Size: no need to find one big block of memory (works better in a fragmented memory).



Speed: predictable - no need to copy big chunks of memory once in a while.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55287602%2fwhat-is-the-fastest-way-to-implement-a-list-and-queue-in-c%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    Assuming you fix your bugs, let's discuss the principles. The biggest performance bug is incrementing size with a constant INC. With this bug, the complexity for inserting n elements is O(n2). For better complexity, reallocate in multiples of 2 or 1.5, after the fix the complexity of inserting n elements becomes O(n), or amortized O(1) for a single insertion.



    The two approaches have been tested extensively with C++: what is faster std:: vector (similar to your stack) or std::list (a doubly linked list). Here is a list of resources:




    • Bjarne Stroustrup, the creator of c++, compared lists and vectors.

    • stack overflow: Relative performance of std::vector vs. std::list vs. std::slist?

    Lists are easier to implement, and have a better predictability (no resizing), but vectors are faster in the stack scenario on average, and more memory efficient.



    Vectors (the stack in the question):



    Size: No need to store pointers to the next element. So it's more efficient.



    Speed: consecutive elements are near each other, resulting in better memory predictability, and higher cache efficiency.



    lists:



    Size: no need to find one big block of memory (works better in a fragmented memory).



    Speed: predictable - no need to copy big chunks of memory once in a while.






    share|improve this answer





























      3














      Assuming you fix your bugs, let's discuss the principles. The biggest performance bug is incrementing size with a constant INC. With this bug, the complexity for inserting n elements is O(n2). For better complexity, reallocate in multiples of 2 or 1.5, after the fix the complexity of inserting n elements becomes O(n), or amortized O(1) for a single insertion.



      The two approaches have been tested extensively with C++: what is faster std:: vector (similar to your stack) or std::list (a doubly linked list). Here is a list of resources:




      • Bjarne Stroustrup, the creator of c++, compared lists and vectors.

      • stack overflow: Relative performance of std::vector vs. std::list vs. std::slist?

      Lists are easier to implement, and have a better predictability (no resizing), but vectors are faster in the stack scenario on average, and more memory efficient.



      Vectors (the stack in the question):



      Size: No need to store pointers to the next element. So it's more efficient.



      Speed: consecutive elements are near each other, resulting in better memory predictability, and higher cache efficiency.



      lists:



      Size: no need to find one big block of memory (works better in a fragmented memory).



      Speed: predictable - no need to copy big chunks of memory once in a while.






      share|improve this answer



























        3












        3








        3







        Assuming you fix your bugs, let's discuss the principles. The biggest performance bug is incrementing size with a constant INC. With this bug, the complexity for inserting n elements is O(n2). For better complexity, reallocate in multiples of 2 or 1.5, after the fix the complexity of inserting n elements becomes O(n), or amortized O(1) for a single insertion.



        The two approaches have been tested extensively with C++: what is faster std:: vector (similar to your stack) or std::list (a doubly linked list). Here is a list of resources:




        • Bjarne Stroustrup, the creator of c++, compared lists and vectors.

        • stack overflow: Relative performance of std::vector vs. std::list vs. std::slist?

        Lists are easier to implement, and have a better predictability (no resizing), but vectors are faster in the stack scenario on average, and more memory efficient.



        Vectors (the stack in the question):



        Size: No need to store pointers to the next element. So it's more efficient.



        Speed: consecutive elements are near each other, resulting in better memory predictability, and higher cache efficiency.



        lists:



        Size: no need to find one big block of memory (works better in a fragmented memory).



        Speed: predictable - no need to copy big chunks of memory once in a while.






        share|improve this answer















        Assuming you fix your bugs, let's discuss the principles. The biggest performance bug is incrementing size with a constant INC. With this bug, the complexity for inserting n elements is O(n2). For better complexity, reallocate in multiples of 2 or 1.5, after the fix the complexity of inserting n elements becomes O(n), or amortized O(1) for a single insertion.



        The two approaches have been tested extensively with C++: what is faster std:: vector (similar to your stack) or std::list (a doubly linked list). Here is a list of resources:




        • Bjarne Stroustrup, the creator of c++, compared lists and vectors.

        • stack overflow: Relative performance of std::vector vs. std::list vs. std::slist?

        Lists are easier to implement, and have a better predictability (no resizing), but vectors are faster in the stack scenario on average, and more memory efficient.



        Vectors (the stack in the question):



        Size: No need to store pointers to the next element. So it's more efficient.



        Speed: consecutive elements are near each other, resulting in better memory predictability, and higher cache efficiency.



        lists:



        Size: no need to find one big block of memory (works better in a fragmented memory).



        Speed: predictable - no need to copy big chunks of memory once in a while.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 21 at 20:30

























        answered Mar 21 at 19:33









        Michael VekslerMichael Veksler

        5,2771724




        5,2771724





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55287602%2fwhat-is-the-fastest-way-to-implement-a-list-and-queue-in-c%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript