typedef struct node {
char *string;
struct node* next;
} node;
typedef struct {
node *head;
node *tail;
node *curr;
} list;
list llInit(){
list *linkedList = malloc(sizeof(list));
linkedList->head = NULL;
linkedList->tail = NULL;
linkedList->curr = NULL;
return *linkedList;
}
int llSize(list *myList){
if (myList->head == NULL){
return 0;
}
int size = 1;
node *instance = myList->head;
while(instance->next != NULL){
instance = instance->next;
size++;
}
return size;
}
int llAddToFront(list *myList,char *toStore){
if (toStore == NULL){
return 0;
}
node *newNode = malloc(sizeof(struct node));
newNode->string = toStore;
newNode->next = myList->head;
myList->head = newNode;
if (myList->tail == NULL){
myList->tail = newNode;
}
return 1;
}
int llAddToBack(list *myList, char *toStore){
if (toStore == NULL){
return 0;
}
if (myList->head == NULL){
return llAddToFront(myList, toStore);
}
node *newNode = malloc(sizeof(struct node));
newNode->string = toStore;
newNode->next = myList->tail;
myList->tail = newNode;
return 1;
}
int main() {
// add one element to front, size should be 1
list two = llInit();
llAddToFront(&two, "one");
if (llSize(&two) != 1){
printf("Test 2: Fail - size should be %d, was %d.\n", 1, llSize(&two));
}
if (one.head == NULL){
printf("ERROR!!!!");
}
if (one.tail.string != "one"){
printf("Test 2: Fail - unexpected tail string.\n");
}
}
这是一个存储字符串的C中的链接列表。C结构的属性为空时,预计是一个参考
出于某种原因,(主)我的头是空的并打印出错信息。我相信我在llAddToFront中正确设置了它。此外,之后的if块会产生分段错误,我不明白为什么。
在发布的代码中,你没有在任何地方声明'one'! –
哇。答案,我会标记它。 – SDK4
@ SDK4这里有一个更好的主意,而不是问多余的问题,并希望其他人为您做调试,为什么不学习如何生成[MCVE](http://stackoverflow.com/help/mcve) ? – Sebivor