2007-c-四
//优化简洁算法
void recycle(LNode *c)
{
int i=1;
LNode *p,*q,*pre;
pre=c;
p=c->next;
while(p!=NULL)
{
if((x&(x-1))==0)//此处采取位运算:如果一个数x为2的平方,那么x&x-1==0
{
printf("%d",p->data);
pre->next=p->next;
q=p;//暂存待释放结点
p=p->next;
free(q);//释放
}
p=p->next;pre=pre->next;//指针下移
++i;//报数增加一
}
if(c->next!=NULL) recycle(c);//圈子里面,还有人继续报数
}
-----------------------------------------------------------------------------------------
#include
#include
#define N 10
typedef struct LNode {
int data;
struct LNode *next;
} LNode;
//建立线性表
LNode* create()
{
LNode *c,*s,*r;
int i;
c=(LNode*)malloc(sizeof(LNode));
c->next=NULL;
r=c;
for(i=1;i<=N;++i) { s=(LNode*)malloc(sizeof(LNode)); s->data=i;
s->next=NULL;
r->next=s;
r=r->next;
}
return c;
}
//删除线性表某个节点
void seaDel(LNode *c,int x)
{
LNode *p,*q;
p=c;
//查找
while(p->next!=NULL)
{
if(p->next->data==x)
break;
p=p->next;
}
//删除
if(p->next!=NULL)
{
q=p->next;
p->next=p->next->next;
free(q);
}
}
//输出
void out(LNode *c)
{
LNode *p;
p=c->next;
while(p!=NULL)
{
printf("%d-->",p->data);
p=p->next;
}
printf("\n");
}
//判断一个数是否为2的平方采用位运算实现
//1.是0.不是
int is2(int x)
{
if((x&(x-1))==0) return 1;//注意&(8级)小于==(7级)
else return 0;
}
//循环删除
void recycle(LNode *c)
{
printf("//////////////////////////////\n");
int i=1;
LNode *q,*p;
p=c->next;
while(p!=NULL)
{
q=p;
p=p->next;
if(is2(i)) {
printf("删除--%d\n",q->data);
seaDel(c,q->data);
}
++i;
}
if(c->next!=NULL) recycle(c);
}
int main() {
LNode *c=create();
out(c);
recycle(c);
}
运行结果