将元素添加到C结构中的序列末尾 [英] adding element to the end of sequence in C struct
问题描述
#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.
我有另一部分代码,用于在序列的前面删除和添加元素,它工作正常,还要注意打印功能也很好.一切都被初始化为 NULL,在程序开始时为零.
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.
推荐答案
first: bottom
指针在 seq_struct
应该初始化为 NULL
first: bottom
pointer in the seq_struct
should be initiated to NULL
第二:在调用之前
seq->bottom->next=endq;
seq->bottom = endq;
你必须检查 seq->bottom
是否不是 NULL
.所以你的代码应该是这样的
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;
您必须考虑使用函数 seq_add_back()
插入链表中的第一个元素.
You have to take in account the first element to insert in your linked list with your function seq_add_back()
.
所以你必须更新你的 seq->bottom
如果它是第一个插入链表的元素.
So you have to update your seq->bottom
also if it's the first elemenent to insert in the linked list.
seq->bottom
应该初始化为 NULL.
The seq->bottom
should be initiated to NULL.
并且您必须在函数seq_add_back()
的末尾添加以下代码:
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;
}
这篇关于将元素添加到C结构中的序列末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!