#include <stdio.h>
#include <stdlib.h>
typedef int E;
/**
* 循环双链表
* 初始化
* 插入元素
* 删除元素
* 求链表总长
* @return
*/
struct ArrayNode{
E e;
struct ArrayNode * prev;
struct ArrayNode * next;
};
typedef struct ArrayNode * Node;
//初始化
_Bool initNode(Node head){
head -> next = head -> prev = head;
return 1;
}
//插入链表
_Bool insertNode(Node head,E e,int index){
if(index < 1) return 0;
Node tmp = head; //作为结束标志
//寻找前驱节点
while(--index){
head = head -> next;
if(head == tmp) return 0;
}
Node newNode = malloc(sizeof(struct ArrayNode));
if(newNode == NULL) return 0;
newNode -> e = e;
newNode -> next = head -> next;
head -> next -> prev = newNode;
head -> next = newNode;
newNode -> prev = head;
return 1;
}
//删除第index位置的链表
_Bool deleteNode(Node head,int index){
if(index < 1) return 0;
//寻找前驱节点
Node tmp = head;
while(--index){
head = head -> next;
if(head == tmp) return 0;
}
if(head -> next == tmp) return 0;
Node node = head -> next;
head -> next -> next -> prev = head;
head -> next = head -> next -> next;
free(node);
return 1;
}
//打印链表第n个位置的前后驱节点
void getNodeE(Node head,int index){
if(index < 1) printf("ERROR");
Node tmp = head;
while(--index){
head = head -> next;
if(head == tmp) printf("ERROR");
}
head = head -> next;
//此时的head是该位置的节点
printf("改位置的前驱节点元素:%d;后驱节点元素:%d\n",head -> prev -> e,head -> next -> e);
}
//求链表总长
int longNode(Node head){
int count = 0;
Node tmp = head->next; // 从头节点的下一个节点开始遍历
while (tmp != head) { // 判断是否回到了头节点
count++;
tmp = tmp->next;
}
return count;
}
//打印链表
void printNode(Node head){
Node tmp = head;
head = head -> next;
while(head != tmp){
printf("%d ",head -> e);
head = head -> next;
}
printf("\n");
}
int main(){
struct ArrayNode head;
initNode(&head);
for(int i = 0; i < 10;i++){
insertNode(&head,(i+1)*10,i+1);
}
printNode(&head);
printf("链表总长:%d\n",longNode(&head));
getNodeE(&head,9);
deleteNode(&head,7);
printNode(&head);
printf("链表总长:%d\n",longNode(&head));
}
标签:Node,tmp,head,return,index,next,链表,精简,C语言
From: https://blog.csdn.net/qq_63456518/article/details/136707165