C 实现的双向循环链表
很久没有用 C 了,都忘了,昨天下午又复习了一下然后实现了这个双向循环链表,后面每种数据结构都会在这里实现记录下来。
开发环境 : sublime+MinGW
#include <stdio.h> #include <stdlib.h>
typedef struct Node { int data; struct Node *perv; struct Node *next; }Node;
int length;
Node* createNode(){ Node * node; node =(Node*)malloc(sizeof(Node)); if(node==NULL){ printf("动态开辟空间失败"); } scanf("%d",&(node->data)); node->perv=NULL; node->next=NULL; return node; }
Node* createList(int n) { Node *tail,*p,*head; head=(Node*)malloc(sizeof(Node)); int i; if(n >= 1) { p = createNode(); head->next = p; p->perv=head; tail = p; } for(i = 2;i <= n;i++) { p = createNode(); tail->next = p; p->perv = tail; tail = p; } head->perv=tail; tail->next=head; length = n; if(n >= 1) return (head); else return 0; }
void insHead(Node* head){ Node *p=createNode(); Node *q; q=head->next; head->next=p; p->perv=head; p->next=q; q->perv=p; ++length; }
void insTail(Node* head){ Node *p=createNode(); Node *tail=head->perv; head->perv=p; p->next=head; tail->next=p; p->perv=tail; ++length; }
Node * getEle(Node* head,int n){ Node *p=head; for (int i = 0; i < n; ++i) { p=p->next; } return p; }
int getLength(){ return length; }
void insAnywhere(Node *head,int n){ Node *newNode=createNode(); Node *currentNode=getEle(head,n); Node *nextNode; nextNode=currentNode->next; currentNode->next=newNode; newNode->perv=currentNode; newNode->next=nextNode; nextNode->perv=newNode; ++length; }
void delNode(Node *head,int n){ Node *delNode=getEle(head,n);
Node *nextNode=delNode->next; delNode->perv->next=nextNode; nextNode->perv=delNode->perv; free(delNode); }
void printlnAll(Node *head){ Node *p=head->next; do{ printf("%d\n", p->data); p=p->next; }while(p!=head); }
int main(int argc, char const *argv[]) {
Node* createList(int n); Node* createNode();
Node *head=createList(3); printf("遍历链表、n"); printlnAll(head); insHead(head); printf("在头插入节点后、n"); printlnAll(head);
insTail(head); printf("在尾插入节点后、n"); printlnAll(head);
printf("---------在第一个元素后面插入元素-----\n"); insAnywhere(head,1); printlnAll(head);
printf("---------删除最后面的节点-------\n"); delNode(head,6); printlnAll(head);
printf("-------删除第一个后面的节点---------\n"); delNode(head,2); printlnAll(head); return 0; }
|
- 线性表

这里面的链式存储结构里面的 静态链表 挺有意思的,不用指针实现链式结构。
线性表的这两种结构实际上是后面其他数据结构的基础,顺序储存结构和链式储存结构也各有优劣。

注:代码中的 String 是我自定义的。
typedef struct{ int length; char *str; int maxLength; }String;
void init(String *s,int max,char * string){ int i; s->maxLength=max; s->length=strlen(string); s->str=(char*)malloc(sizeof(char)*max); for(i=0;i<s->length;i++){ s->str[i]=string[i]; } }
|
感谢鼓励