本博客为《数据结构与算法-C语言版》(传智播客编著)的学习笔记,如涉及版权问题,请告知本人,本人会立即删除。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct _Header
{
int len;
struct _Node* next;
};
struct _Node
{
int data;
struct _Node* next;
};
typedef struct _Header Head;
typedef struct _Node Node;
Head* CreteList()
{
Head* ph=(Head*)malloc(sizeof(Head));
if(ph!=NULL)
{
ph->len=0;
ph->next=NULL;
return ph;
}
return NULL;
}
Node* FindNodeByVal(Head* ph,int val)
{
if(ph==NULL)
{
return NULL;
}
Node* pTmp=ph->next;
do
{
if(pTmp->data==val)
{
return pTmp;
}
pTmp=pTmp->next;
}while(pTmp->next!=ph->next);
return NULL;
}
void CircleListInsert(Head* ph,int pos,int val)
{
if(ph==NULL || pos<0 || pos>ph->len)
{
return;
}
Node* pval=(Node*)malloc(sizeof(Node));
pval->data=val;
if(ph->len==0)
{
ph->next=pval;
pval->next=pval;
}
else
{
Node* pRear=ph->next;
if(pos==0)
{
while(pRear->next!=ph->next)
{
pRear=pRear->next;
}
pval->next=ph->next;
ph->next=pval;
pRear->next=pval;
}
else
{
Node* pCur=ph->next;
for(int i=1;i<pos;i++)
{
pCur=pCur->next;
}
pval->next=pCur->next;
pCur->next=pval;
}
}
ph->len++;
return;
}
void CircleListDelete(Head* ph,int val)
{
if(ph==NULL || ph->len==0)
{
return;
}
Node* pRear=ph->next;
while(pRear->next!=ph->next)
{
pRear=pRear->next;
}
Node* pval=FindNodeByVal(ph, val);
if(pval==NULL)
{
return;
}
if(pval==ph->next)
{
ph->next=pval->next;
pRear->next=pval->next;
}
else
{
Node* pPre=ph->next;
for(int i=0;i<ph->len;i++)
{
if(pPre->next==pval)
{
pPre->next=pval->next;
}
pPre=pPre->next;
}
}
free(pval);
ph->len--;
}
Node* FindNodeByPos(Head* ph,int pos)
{
if(ph==NULL)
{
return NULL;
}
if(pos<0 || pos>ph->len)
{
return NULL;
}
Node* pTmp=ph->next;
if(pTmp!=NULL)
{
for(int i=0;i<ph->len;i++)
{
if(i==pos)
{
return pTmp;
}
pTmp=pTmp->next;
}
}
return NULL;
}
int main(int argc, const char * argv[]) {
Head* ph=CreteList();
CircleListInsert(ph, 0, 9);
CircleListInsert(ph, 1, 6);
CircleListInsert(ph, 2, 7);
CircleListInsert(ph, 3, 8);
CircleListInsert(ph, 4, 9);
CircleListInsert(ph, 5, 10);
CircleListDelete(ph, 9);
CircleListDelete(ph, 8);
for(int i=0;i<ph->len;i++)
{
printf("%d",FindNodeByPos(ph, i)->data);
}
return 0;
}