#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void printList(struct Node *pHead)
{
struct Node *p = pHead->next;
while(p)
{
printf("%d\n",p->data);
p = p->next;
}
}
int isEmpty(struct Node *pHead)
{
return pHead->next == NULL;
}
size_t length(struct Node *pHead)
{
struct Node *p = pHead->next;
size_t counter = 0;
while(p)
{
p = p->next;
++counter;
}
return counter;
}
void push_frnot(struct Node *pHead,int n)
{
struct Node *pNew = malloc(sizeof(struct Node));
pNew->data = n;
pNew->next = pHead->next;
pHead->next = pNew;
}
void push_back(struct Node *pHead,int n)
{
if(isEmpty(pHead))
{
push_frnot(pHead,n);
}
else
{
struct Node *pNew = malloc(sizeof(struct Node));
pNew->data = n;
struct Node *p = pHead->next;
while(p->next)
{
p = p->next;
}
p->next = pNew;
pNew->next = NULL;
}
}
void pop_front(struct Node *pHead)
{
if(!isEmpty(pHead))
{
struct Node *p = pHead->next;
pHead->next = p->next;
free(p);
}
}
void pop_back(struct Node *pHead)
{
if(length(pHead) >= 2)
{
struct Node *p = pHead->next;
while(p->next->next)
{
p = p->next;
}
free(p->next);
p->next = NULL;
}
else if(length(pHead) < 2)
{
pop_front(pHead);
}
}
void destroyList(struct Node *pHead)
{
while(!isEmpty(pHead))
{
pop_front(pHead);
}
}
int main(void)
{
struct Node head;
head.next = NULL;
struct Node *pHead;
pHead = &head;
push_frnot(pHead,1);
push_frnot(pHead,2);
push_frnot(pHead,3);
push_back(pHead,5);
pop_front(pHead);
pop_back(pHead);
printList(pHead);
destroyList(pHead);
printf("length = %u\n",length(pHead));
return 0;
}