如何在C列表中添加和使用尾部

  • 本文关键字:尾部 添加 列表 c
  • 更新时间 :
  • 英文 :


所以我试图创建列表。在列表的前面添加数字的功能正在工作,但我有麻烦添加一个数字到列表的末尾。我知道尾部改变数据值,但我不知道我应该如何打印它,并使用它来改变我的列表。

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

struct list
{
int data;
struct lista *next;
};
struct listWsk
{
struct list *head,*tail;
};
int create(struct listWsk *list, int data)
{
struct list *new_front = malloc(sizeof(struct list));
struct list *new_back = malloc(sizeof(struct list));
if(NULL != new_front && NULL != new_back)
{
new_front->data = data;
new_back->data = data;
list->head = new_front;
list->tail = new_back;
list->tail->next = NULL;
list->head->next = NULL;
return 1;
}
};
void print(struct listWsk list)
{
while(list.head != NULL)
{
printf("%d ",list.head->data);
list.head = list.head->next;
}
}
void front(struct listWsk *list, int data)
{
struct list *new = malloc(sizeof(struct list));
if(new != NULL)
{
new ->data = data;
new ->next = list ->head;
list ->head = new;
}
};
void back(struct listWsk *list,int data)
{
struct list *new = malloc(sizeof(struct list));
if(new != NULL)
{
new -> data = data;
new ->next = NULL;
list ->tail->next = new;
list->tail = new;
}
}
int main()
{

struct listWsk lista = {NULL,NULL};
create(&lista,5);
front(&lista,8);
back(&lista,3);
print(lista);

}

输出:8 5,我不知道如何将尾号添加到列表中。

更正代码

struct list
{
int data;
struct list* next; <<<<==== you had lista here - surpised it even compiled
};
struct listWsk
{
struct list* head, * tail;
};
int create(struct listWsk* list, int data)
{
// you dont need 2 nodes here just one
// head and tail both point to it
struct list* new_front = malloc(sizeof(struct list));
if (NULL != new_front)
{
new_front->data = data;
new_front->next = NULL;
list->head = new_front;
list->tail = new_front;
return 1;
}
return 0; <<< === you were not returning a value here
};
void print(struct listWsk list)
{
while (list.head != NULL)
{
printf("%d ", list.head->data);
list.head = list.head->next;
}
}
void front(struct listWsk* list, int data)
{
struct list* new = malloc(sizeof(struct list));
if (new != NULL)
{
new->data = data;
new->next = list->head;
list->head = new;
}
};
void back(struct listWsk* list, int data)
{
struct list* new = malloc(sizeof(struct list));
if (new != NULL)
{
new->data = data;
new->next = NULL;
list->tail->next = new;
list->tail = new;
}
}
int main()
{
struct listWsk lista = { NULL,NULL };
create(&lista, 5);
front(&lista, 8);
back(&lista, 3);
// I added a few more test cases
front(&lista, 81);
back(&lista, 32);
print(lista);

}

你的问题是你有两个节点而不是一个在你的列表中只有一个条目,事情就会变得混乱

最新更新