循环链表实现增、删、改、查等功能

来源:互联网 发布:美国的军事实力知乎 编辑:程序博客网 时间:2024/06/05 03:02

循环链表有一个头指针指向头结点,如下图所示:


头结点不保存数据,所以head->next中的节点中保存数据。

代码实现:

#include <stdio.h>#include <stdlib.h>typedef struct node{//节点类型int data;//保存数据struct node* next;//指向下一个节点}Node;//typedef struct node Node;#define SIZE sizeof(Node)Node* head = NULL;//head保存头节点地址 结节点//2 创建节点的函数Node* creat_node(int d){/*创建一个节点,这个节点指向头节点*/Node* pn = malloc(SIZE);pn->data = d;pn->next = head->next;return pn;}//3 使用数组初始化链表void init_list(int* p,int len){if(len<1)return;int i;Node* ph = NULL;Node* pn = NULL;ph = creat_node(p[0]);//p指向头节点ph->next = ph;//头节点指向头节点head->next = ph;//结节点 指向 头节点for(i=1;i<len;i++){//其他节点,其他节点创建的时候就已经指向了头节点pn = creat_node(p[i]);ph->next = pn;ph = ph->next;}}//4 遍历循环单链表void travel(){Node* p = head->next;printf("list:");while(p->next != head->next){printf("%d ",p->data);p = p->next;}printf("%d\n",p->data);}void show(int n){Node* p = head->next;printf("list:");int i;for(i=0;i<n;i++){printf("%d ",p->data);p = p->next;}printf("\n");}//5 添加一个节点到循环单链表末尾void add(int d){//1 创建新节点Node* pn = creat_node(d);//2 找到链表的尾节点Node* p = head->next;while(p->next != head->next){p = p->next;}//3 新节点成为尾节点:把新节点链接到链表的尾节点之后p->next = pn;}//6 插入一个节点成为循环单链表的倒数第2个节点void set(int d){int count = 0;int i;//1 创建新节点Node* pn = creat_node(d);//2 找到倒数第2个节点//2.1 得到链表节点总数Node* p = head->next;while(p->next != head->next){count++;p = p->next;}//2.2 p指向倒数第2个节点p = head->next;for(i=1;i<count;i++)p = p->next;//3 插入到倒数第2个节点之后//3.1 pn->next = p->next;//3.2 p->next = pn;}//7 找到数据为d的节点并返回其地址Node *travel(Node* p,int d){while(1){if(p->data==d)return p;p=p->next;//找过一轮了if((head->next)->data==p->data && p->data!=d ){return NULL;}}}//8 删除数据为d的节点Node *travel(Node* p,Node* q,int d){while(1){if(q->data==d){q=p->next;p->next=q->next;free(q);q=NULL;}p=p->next;if((head->next)->data==p->data && p->data!=d ){return NULL;}}}int main(){int a[5] = {11,22,33,44,55};//1 创建头节点 头节点不保存数据  一个结。//这个结保存头节点地址,尾节点指向头节点。head = (Node*)malloc(SIZE);head->data = 0;head->next = NULL;init_list(a,5);travel();set(100);show(10);return 0;}


阅读全文
0 0
原创粉丝点击