#ifndef BOTHWAYLIST
#define BOTHWAYLIST
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE
{
struct NODE* last; //指向前一个节点
void* data;
struct NODE* next;//指向后一个节点
}Node;
typedef struct LIST
{
Node* head; //链表的头部
Node* tail; //链表的尾部
int len;
}List;
typedef void(PRINT)(void* data);
Node* InitList(); //初始化链表
void InsertList(List* list, void* data, int pos); //插入链表
void RemoveList(List* list, int pos); //移除pos位置的数据
void PrintList(List* list,PRINT print); //打印数据
void FreeList(List* list); //释放链表
#endif
#include "bothwaylist.h"
Node* InitList()
{
List* list = (List*)malloc(sizeof(List));
list->head = (Node*)malloc(sizeof(Node));
list->tail = (Node*)malloc(sizeof(Node));
list->head->next = list->tail;
list->head->last = NULL;
list->head->data = NULL;
list->tail->last = list->head;
list->tail->next = NULL;
list->len = 0;
return list;
}
void InsertList(List* list, void* data, int pos)
{
if ( list == NULL || data == NULL )
{
printf("链表为空");
return;
}
if ( pos < 0 || pos > list->len )
{
printf("插入下标错误\n");
return;
}
Node* newnode = (Node*)malloc(sizeof(Node));
newnode->data = data;
Node* pCurrent = list->head;
for (int i = 0; i < pos; i++)
{
pCurrent = pCurrent->next;
}
newnode->last = pCurrent;
pCurrent->next->last = newnode;
newnode->next = pCurrent->next;
pCurrent->next = newnode;
list->len++;
//printf("%d", list->len);
}
void RemoveList(List* list, int pos)
{
if ( list == NULL )
{
printf("链表为空");
return;
}
if (pos < 0 || pos > list->len)
{
printf("下标错误\n");
return;
}
Node* pCurrent = list->head;
for (int i = 0; i < pos; i++)
{
pCurrent = pCurrent->next;
}
Node* pDel = pCurrent->next;
pCurrent->next = pCurrent->next->next;
free(pDel);
list->len--;
}
void PrintList(List* list,PRINT* print)
{
Node* pCurrent = list->head->next;
for (int i = 0; i < list->len; i++)
{
print(pCurrent->data);
pCurrent = pCurrent->next;
}
pCurrent = list->tail->last;
putchar('\n');
while (pCurrent != list->head)
{
print(pCurrent->data);
pCurrent = pCurrent->last;
}
}
void FreeList(List* list)
{
if (list == NULL)
{
printf("链表为空");
return;
}
Node* pCurrent = list->head;
for (int i = 0; i < list->len; i++)
{
Node* p = pCurrent;
pCurrent = pCurrent->next;
free(p);
}
}
#include "bothwaylist.h"
typedef struct MYDATA
{
int n;
}mydata;
void Print(void* data)
{
mydata* newdata = (mydata*)data;
printf("%d ", newdata->n);
}
int main()
{
mydata data1;
mydata data2;
mydata data3;
mydata data4;
mydata data5;
data1.n = 1;
data2.n = 2;
data3.n = 3;
data4.n = 4;
data5.n = 5;
List* list = InitList();
InsertList(list, &data1, 0);
InsertList(list, &data2, 1);
InsertList(list, &data3, 2);
InsertList(list, &data4, 3);
InsertList(list, &data5, 4);
//RemoveList(list, 0);
PrintList(list, Print);
//FreeList(list);
system("pause");
return 0;
}