#include"stdlib.h"
typedef struct listnode{
char* data;
struct listnode* next;
}listnode;
listnode* init()
{
listnode* head = (listnode*)malloc(sizeof(listnode));
if (head == NULL){ return; }
head->data = NULL;
head->next = head;
return head;
}
listnode* createnode(char* value)
{
if (value == NULL){ return; }
listnode* tmp = (listnode*)malloc(sizeof(listnode));
if (tmp == NULL){ return; }
tmp->data = value;
tmp->next = NULL;
return tmp;
}
void pushfront(listnode* list,char* value)
{
if (list == NULL||value==NULL)
{
return;
}
listnode* tmp = createnode(value);
tmp->next = list->next;
list->next = tmp;
}
void pushback(listnode* list,char* value)
{
if (list == NULL || value == NULL)
{
return;
}
listnode* tmp =list->next;
while (tmp->next != list)
{
tmp = tmp->next;
}
listnode* pushnode = createnode(value);
tmp->next = pushnode;
pushnode->next = list;
}
void popfront(listnode* list)
{
if (list == NULL){ return; }
listnode* tmp = list->next;
list->next = tmp->next;
free(tmp);
}
void popback(listnode* list)
{
if (list == NULL){ return; }
listnode* tmp1 = list;
listnode* tmp2 = NULL;
while (tmp1->next->next!=list)
{
tmp1 = tmp1->next;
}
tmp2 = tmp1->next;
tmp1->next = tmp1->next->next;
free(tmp2);
}
void insert(listnode* list, char* value, int pos)
{
if (list == NULL || value == NULL || pos<0){ return; }
int length = getlength(list);
if (pos >length+1)
{
pos = length+1;
}
listnode* tmp = list;
for (int i = 1; i<pos; i++)
{
tmp = tmp->next;
}
listnode* insertnode = createnode(value);
insertnode->next = tmp->next;
tmp->next = insertnode;
}
int getlength(listnode* list)
{
if (list == NULL)
{
return;
}
int i = 0;
listnode* tmp = list;
for (; tmp->next != list; i++)
{
tmp = tmp->next;
}
return i;
}
int printbylink(listnode* list)
{
if (list == NULL)
{
return;
}
int i = 0;
listnode* tmp = list;
for (; tmp->next != list;i++)
{
tmp = tmp->next;
printf("%s\n",tmp->data);
}
return i;
}
void main(){
listnode* list = init();
pushfront(list,“aaa”);
pushfront(list,“bbb”);
pushfront(list,“ccc”);
pushback(list,“ddd”);
int length1=printbylink(list);
printf(“长度为:%d\n”, length1);
popfront(list);
popback(list);
int length2 = printbylink(list);
printf(“长度为:%d\n”,length2);
insert(list,“1”,2);
insert(list,“2”,100);
insert(list,“3”,1);
int length3 = printbylink(list);
printf(“长度为:%d\n”, length3);
system(“pause”);
}