我正在尝试使用各种推送和弹出功能来学习链表,但我无法从链表的尾部弹出元素。谁能帮我解决popBack
功能?
我试过类似的东西:
typedef struct
{
float val;
}data;
typedef struct nodePtr
{
struct nodePtr *next;
data *d;
}node;
typedef struct
{
node *head;
node *tail;
}linkList;
linkList* createlinkList()
{
linkList *ll = (linkList*)malloc(sizeof(linkList));
ll->head = NULL;
ll->tail = NULL;
return ll;
}
node* createNode(data *d)
{
node *nd = (node*)malloc(sizeof(node));
nd-> d = d;
nd-> next = NULL;
return nd;
}
data* createData(float val)
{
data *iptr = (data*)malloc(sizeof(data));
iptr->val = val;
return iptr;
}
void addFront(linkList *ll,data *d)
{
node *new_node = createNode(d);
if(ll->head == NULL && ll->tail == NULL )
{
ll->head = new_node;
ll->tail = new_node;
}
else
{
new_node->next = ll->head;
ll->head = new_node;
}
}
void addBack(linkList *ll,data *d)
{
node *new_node = createNode(d);
if(ll->head == NULL && ll->tail == NULL )
{
ll->head = new_node;
ll->tail = new_node;
}
else
{
ll->tail->next = new_node;
ll->tail = new_node;
}
}
void printList(linkList *ll)
{
node *temp = ll->head;
while(temp!=NULL)
{
printf("%f\n",temp->d->val);
temp = temp->next;
/*if(temp==ll->tail)
{
printf("%f\n",temp->d->val);
break;
}*/
}
}
int listSize(linkList *ll)
{
int size=0;
node *count;
for(count=ll->head;count!=NULL;count=count->next)
{
size++;
}
return size;
}
data* popFront(linkList *ll)
{
data *popf;
popf = ll->head->d;
node *temp = ll->head;
ll->head = ll->head->next;
free(temp);
return popf;
}
**data* popBack(linkList *ll)
{
data *popb;
popb = ll->tail->d;
while(ll->head->next!=NULL)
{
printf("%f\n",ll->head->next->d->val);
if(ll->head->next==NULL)
{
node* temp = ll->head->next;
free(temp);
}
}
return popb;
}**
int main(int argc, char* argv[])
{
linkList *ll = createlinkList();
data *iptr = createData(11.10);
addFront(ll,iptr);
data *iptr1 = createData(10.10);
addFront(ll,iptr1);
data *iptr2 = createData(12.10);
addBack(ll,iptr2);
printList(ll);
int count = listSize(ll);
printf("%d\n",count);
popFront(ll);
printList(ll);
popBack(ll);
printList(ll);
return 0;
}