一、代码描述
C语言 双向循环链表 其中包括:初始化,头插,尾插,头删,尾删,查询…
二、参考代码
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
//双向循环链表
typedef int LTDataType;
typedef struct ListNode
{
LTDataType data;
struct ListNode* next;
struct ListNode* pre;
}ListNode;
ListNode* ListInit() {
ListNode* phead = (ListNode*)malloc(sizeof(ListNode));
phead->next = phead;
phead->pre = phead;
return phead;
}
ListNode* ListFind(ListNode* phead, LTDataType x) {
assert(phead);
printf("查找\n");
ListNode* cur = phead->next;
while (cur != phead) {
if (cur->data == x) {
return cur;
}
cur = cur->next;
}
return NULL;
}
void ListPushBack(ListNode* phead, LTDataType x) {
assert(phead);
ListNode* tail = phead->pre;
ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
newnode->data = x;
//Link to
tail->next = newnode;
newnode->pre = tail;
newnode->next = phead;
phead->pre = newnode;
}
void ListPri(ListNode* phead)
{
assert(phead);
ListNode* cur = phead->next;
while (cur != phead) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
void ListPushFront(ListNode* phead, LTDataType x)
{
assert(phead);
ListNode* tail = phead->next;
ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
newnode->data = x;
//Link to
newnode->pre = phead;
newnode->next = tail;
phead->next = newnode;
tail->pre = newnode;
}
void ListPopBack(ListNode* phead)
{
printf("尾删\n");
assert(phead);
assert(phead->next != phead);
ListNode* tail = phead->pre;
ListNode* tailpre = tail->pre;
tailpre->next = phead;
phead->pre = tail;
free(tail);
}
void ListInsert(ListNode* pos, LTDataType x) {
assert(pos);
printf("插入\n");
ListNode* PosPre = pos->pre;
ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
newnode->data = x;
//posPre newnode pos
PosPre->next = newnode;
newnode->next = pos;
pos->pre = newnode;
newnode->pre = PosPre;
}
void ListErase(ListNode* pos) {
assert(pos);
//......
}
void ListPopFront(ListNode* phead)
{
printf("头删\n");
assert(phead);
assert(phead->next != phead);
ListNode* cur = phead->next;
phead->next = cur->next;
cur->pre = phead;
free(cur);
}
void Test()
{
ListNode* plist = ListInit();
printf("尾插\n");
ListPushBack(plist, 1);
ListPushBack(plist, 2);
ListPushBack(plist, 3);
ListPushBack(plist, 4);
ListPri(plist);
ListPopBack(plist);
ListPri(plist);
printf("头插\n");
ListPushFront(plist, 0);
ListPri(plist);
ListPopFront(plist);
ListPri(plist);
}
int main() {
Test();
return 0;
}