#include<stdio.h>
#include<stdlib.h>
typedef struct
{
char dat;
struct NODE *next;
struct NODE *prev;
}NODE;
NODE *head=NULL;
NODE *tail=NULL;
int len =0;
NODE* createNODE(char dat){
NODE *ptr;
ptr = malloc(sizeof(NODE));
if(ptr == NULL){
exit(1);
}
ptr->dat=dat;
ptr->prev=NULL;
ptr->next=NULL;
return ptr;
}
void addFirst(char dat)
{
NODE *ptr=createNODE(dat);
if(len)
{
ptr->next=head;
head->prev=ptr;
head=ptr;
}else
{
head=ptr;
tail=ptr;
}
len++;
}
NODE * Find ( char dat )
{
//在链表中从头搜索其数据值为value的结点
NODE * p =head->next;
//检测指针 p 指示第一个结点
while ( p != NULL && p->dat != dat )
p = p->next;
return p;
}
NODE * get(int index)
{
int i=0,n=0;
NODE *ptr=head;
if(index<0||index>len-1)
{
printf("index is illegal!\n");
return NULL;
}
if(index<len/2)
{
for(;i<index;i++)
{
ptr=ptr->next;
n++;
}
}
else if(index>=len/2)
{
ptr=tail;
for(i=len;i>index;i--)
{
ptr=ptr->prev;
n++;
}
}
printf("%d\n",n);
return ptr;
}
void add(char dat, int index)
{
NODE *ptr,*prevPtr,*nextPtr;
if(len==0)
{
printf("the link is NULL\n");
return ;
}
if(index<0||index>len-1)
{
printf("index is illegal!\n");
return ;
}
ptr=createNODE(dat);
if(index == 0)
{
addFirst(dat);
}else
{
prevPtr= get(index-1);
nextPtr=prevPtr->next;
ptr->next=prevPtr->next;
nextPtr->prev=ptr;
prevPtr->next=ptr;
ptr->prev=prevPtr;
len++;
}
}
void addLast(char dat)
{
if(len ==0)
{
addFirst(dat);
}
else
{
NODE *ptr=createNODE(dat);
tail->next=ptr;
ptr->prev=tail;
tail=ptr;
len++;
}
}
void delete(int index)
{
NODE *temp=head,*prevPtr =NULL,*curPtr =NULL,*nextPtr=NULL;
if(index<0||index>len-1)
{
printf("index is illegal!\n");
return ;
}
if(index==0)
{
head=head->next;
free(temp);
}
else
{
prevPtr=get(index-1);
curPtr=prevPtr->next;
nextPtr=curPtr->next;
if(nextPtr==NULL)
{
tail=prevPtr;
}
prevPtr->next=nextPtr;
free(curPtr);
}
len--;
return ;
}
void travel()
{
int i=len;
NODE *ptr=head;
while(i--)
{
printf("addr:%x,%c,next:%x\n",ptr,ptr->dat,ptr->next);
ptr=ptr->next;
}
}
void create_circle_link()
{
tail->next=head;
}
void list_jose(int k,int m)
{
int i;
NODE *p,*r;
r=head;
r=get(k-1);
printf("k=%d\n",k);
while(r->next!=r)
{
for(i=0;i<m-1;i++)
{
r=r->next;
}
p=r->next;
r->next=p->next;
printf("%d\n",r->dat);
free(p);
p=NULL;
travel();
}
}
void main()
{
NODE *p;
addFirst('1');
addFirst('2');
addFirst('3');
addFirst('4');
addFirst('5');
addFirst('1');
addFirst('2');
addFirst('3');
addFirst('4');
addFirst('5');
p=get(9);
//add('A',2);
travel();
//p=Find('3');
printf("%c\n",p->dat);
//create_circle_link();
//list_jose(1,2);
return ;
}
C链表
最新推荐文章于 2024-02-27 17:53:45 发布