adding element to the end of sequence in C struct

2019-08-15 06:26发布

问题:

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

    typedef struct stack_node {
       ETYPE data;
       struct stack_node *prev, *next;
    }NODE;

    struct seq_struct {
       // "Container" struct
       NODE* top, *bottom;
       int size;
    };

/**
* DESCRIPTION:  adds a new element to the "back" of
*  the seq
*
*   [2 4]
*        add_back 7
*            [2 4 7]
*
*
*/
void seq_add_back(Seq seq, ETYPE val){
NODE* endq = malloc(sizeof(NODE));
   endq->next =NULL;

   endq->prev = seq->bottom;
   endq->data = val;

   seq->bottom->next=endq;
   seq->bottom = endq;

   seq->size++;
   return;
}

I need your help in understanding what is wrong with my code. It doesn't add a new element to the sequence at the end like it should been.

I have another portion of code, for deleting and adding elements to the front of of the sequence and it works fine, also to note print function is fine too. everything beeing initialized to NULL, and zero at the start of the program.

回答1:

first: bottom pointer in the seq_struct should be initiated to NULL

second: before calling

seq->bottom->next=endq;
seq->bottom = endq;

you have to check if seq->bottom is not NULL. so your code should looks like this

if (seq->bottom != NULL)
    seq->bottom->next=endq;
seq->bottom = endq;

You have to take in account the first element to insert in your linked list with your function seq_add_back().

So you have to update your seq->bottom also if it's the first elemenent to insert in the linked list.

The seq->bottom should be initiated to NULL.

and you have to add the following code at the end of your function seq_add_back():

if (seq->top == NULL)
    seq->top = endq;

So as summary your function should look like this:

void seq_add_back(Seq seq, ETYPE val){
   NODE* endq = malloc(sizeof(NODE));
   endq->next =NULL;

   endq->prev = seq->bottom;
   endq->data = val;

   if (seq->bottom != NULL)
      seq->bottom->next=endq;
   seq->bottom = endq;

   if (seq->top == NULL)
      seq->top = endq;

   seq->size++;
   return;
}