adding element to the end of sequence in C struct

送分小仙女□ 提交于 2020-01-05 07:41:30

问题


    #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;
}


来源:https://stackoverflow.com/questions/19287686/adding-element-to-the-end-of-sequence-in-c-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!