在C struct中将元素添加到序列的前面

时间:2013-10-11 01:54:41

标签: c struct sequence typedef

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

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

void seq_add_front(Seq seq, ETYPE val){

    /* create a node to be added to the front of the sequence */
    NODE* topq = malloc(sizeof(NODE));

    topq->data = val;

if(seq->top==NULL){
    topq->prev=NULL;
    topq->next=NULL;
    seq->top = topq;
    seq->bottom=topq;

}
   else{
    topq->prev=NULL;
    topq->next=NULL;

    seq->top=topq;
    seq->bottom=topq->next;
    //seq->top=topq;


   }

   /* increment the size */
   seq->size++;

}

我需要你的帮助来理解我的其他声明有什么问题。如果(seq-> top!= NULL),我无法弄清楚如何保留前一个值。

我的首发问题是adding element to the end of sequence in C struct并且被此功能覆盖了。现在我重写了它,并且需要找到一种方法来保持seq-> bottom的值,同时添加新值。

1 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

   else {
    topq->prev=NULL; // make sure our prev is null
    topq->next = seg->top; // set our next to the current top
    seg->top->prev = topq; // set the current top to point back to us
    seq->top=topq; // set current top to be us
   }

请注意,底部不需要在此else子句中更改