#include <stdio.h>
#include <stdlib.h>
typedef int element;
typedef struct ListNode
{
element data;
struct ListNode* Link;
}ListNode;
typedef struct
{
ListNode* tail;
int size;
}ListType;
void init(ListType* L)
{
L->tail = NULL;
L->size = 0;
}
int isEmpty(ListType* L)
{
return L->tail == NULL;
}
void insertLast(ListType* L, element e)
{
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->data = e;
if (isEmpty(L))
{
node->Link = node;
L->tail = node;
}
else
{
node->Link = L->tail->Link;
L->tail->Link = node;
L->tail = node;
}
L->size++;
}
void insertFirst(ListType* L, element e)
{
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->data = e;
if (isEmpty(L))
{
node->Link = node;
L->tail = node;
}
else
{
node->Link = L->tail->Link;
L->tail->Link = node;
}
L->size++;
}
void print(ListType* L)
{
if (isEmpty(L))
return;
ListNode* p = L->tail->Link;
for (int i = 1; i <= L->size; i++)
{
printf("[%d] =>", p->data);
p = p->Link;
}
printf("\b\b\b \n");
}
void print2(ListType* L)
{
if (isEmpty(L))
return;
ListNode* p = L->tail;
do
{
printf("[%d] =>", p->Link->data);
p = p->Link;
} while (p != L->tail);
printf("\b\b\b \n");
}
element deleteFirst(ListType* L)
{
if (isEmpty(L))
return -1;
ListNode* p = L->tail;
ListNode* q = p->Link;
element e = q->data;
if (p == q)
L->tail = NULL;
else
p->Link = q->Link;
L->size--;
free(q);
return e;
}
element deleteLast(ListType* L)
{
if (isEmpty(L))
return -1;
ListNode* p = L->tail;
ListNode* q = p->Link;
element e = p->data;
if (p == q)
L->tail = NULL;
else
{
while (q->Link != p)
q = q->Link;
q->Link = p->Link;
L->tail = q;
}
L->size--;
free(p);
return e;
}
int main()
{
ListType L;
init(&L);
printf("InsertLast --------------\n");
insertLast(&L, 10); print2(&L);
insertLast(&L, 30); print2(&L);
insertLast(&L, 20); print2(&L);
printf("\n\nInsertFirst --------------\n");
insertFirst(&L, 40); print(&L);
insertFirst(&L, 60); print(&L);
insertFirst(&L, 50); print(&L);
printf("[%d] is deleted ", deleteFirst(&L)); print2(&L);
printf("[%d] is deleted ", deleteLast(&L)); print2(&L);
return 0;
}