AfxStd.h
#ifndef AfxStd #define AfxStd #include<stdio.h> #include<stdlib.h> #include<string.h> #include<malloc.h> #endif // !USUSL_H
DList.h
#ifndef DLIST_H #define DLIST_H #include "AfxStd.h" typedef int ElemType; typedef struct DLNode { DLNode *pre; ElemType data; DLNode *next; }DLNode, *DList; struct DUList { DList head; int cursize; }; DLNode *BuyNode(DLNode *ptag = NULL, DLNode *ntag = NULL);/*避免编译上的二义性,在声明时给默认值*/ void FreeNode(DList p); void InitList(DUList &L); void DestoryList(DUList &L); int GetLength(DUList &L); bool DlistEmpty(DUList &L); bool Insert(DUList &L, int pos, ElemType e); bool push_back(DUList &L, ElemType e); bool push_front(DUList &L, ElemType e); bool InsertElem(DUList &L, DLNode *ptr, ElemType e); bool DelectElem(DUList &L, DLNode *ptr); bool pop_back(DUList &L); bool pop_front(DUList &L); bool Declect(DUList &L, int pos); #endif // !1
DList.cpp
#include "Dlist.h" /*购买节点*/ DLNode *BuyNode(DLNode *ptag, DLNode *ntag) { DList s = (DList)malloc(sizeof(DLNode)); if (s == NULL) { exit(1); } memset(s, 0, sizeof(DLNode)); s->pre = ptag == NULL ? s : ptag; s->next = ntag == NULL ? s : ntag; return s; } /*释放节点*/ void FreeNode(DList p) { free(p); } /*初始化节点*/ void InitList(DUList &L) { L.cursize = 0; L.head = BuyNode(); //L.head->pre = L.head; //L.head->next = L.head; } /*摧毁链表*/ void DestoryList(DUList &L) { L.cursize = 0; free(L.head); L.head = NULL; } /*按位置增加一个节点*/ bool Insert(DUList &L, int pos, ElemType e) { if (pos<1 || pos>L.cursize + 1) { printf("插入位置有误!"); return false; } DLNode *p = L.head; while (1 != pos--) /*先参与运算再自减*/ { p = p->next; } InsertElem(L, p->next, e); /* DLNode *newNode = BuyNode(p, p->next); newNode->data = e; L.cursize++; */ return true; } /*在某节点之前加入节点*/ bool InsertElem(DUList &L, DLNode *ptr, ElemType e) { if (ptr == NULL) { return false; } /* DLNode *newNode = BuyNode(ptr->pre, ptr); newNode->data = e; ptr->pre->next = newNode; ptr->next = newNode; L.cursize++; */ ptr->pre = BuyNode(ptr->pre, ptr); ptr = ptr->pre; ptr->pre->next = ptr; ptr->data = e; L.cursize++; return true; } /*头插*/ bool push_front(DUList &L, ElemType e) { InsertElem(L, L.head->next, e); //Insert(L, L.cursize + 1, e); return true; } /*尾插*/ bool push_back(DUList &L, ElemType e) { InsertElem(L, L.head, e); //Insert(L,1,e); return true; } /*删除某节点*/ bool DelectElem(DUList &L, DLNode *ptr) { if (ptr == NULL) { return false; } ptr->pre->next = ptr->next; ptr->next->pre = ptr->pre; free(ptr); L.cursize--; return true; } /*尾删*/ bool pop_back(DUList &L) { DelectElem(L, L.head->pre); return true; } /*头删*/ bool pop_front(DUList &L) { DelectElem(L, L.head->next); return true; } /*按位置删除节点*/ bool Declect(DUList &L, int pos) { if (pos<1 || pos>L.cursize) { printf("删除位置有误!"); return false; } DLNode *p = L.head; while (1 != pos--) /*先参与运算再自减*/ { p = p->next; } DelectElem(L, p->next); return true; } /*判空*/ bool DlistEmpty(DUList &L) { return L.cursize == 0; } /*链表的长度*/ int GetLength(DUList &L) { return L.cursize; }