您的位置:首页 > 其它

链表中递归查找元素,非递归查找元素 以及基数排序(未完成)josephus问题(未完成)

2014-03-26 22:45 417 查看
#ifndef CIRCLECHAIN_H
#define CIRCLECHAIN_H
struct NODE;
struct LIST;
typedef NODE* node;
typedef LIST* list;
typedef int elemtype;
//单链表
struct NODE
{
int n;
node next;
};
struct LIST
{
node tail;
node header;
};
//初始化链
list creatList();
//在末尾添加一个节点添加成功返回1,添加失败返回0
int addNode(elemtype n,list l);
//打印链表所有元素
void printlist(list l);
//判断是否为最后一个链表
bool isLast(node n,list l);
#endif



具体实现
#include "circlechain.h"
#include "stdlib.h"
#include "stdio.h"
list creatList()
{
list l=(list)malloc(sizeof(list));
node n;
n=(node)malloc(sizeof(node));
n->next=NULL;
l->header=l->tail=n;
return l;
}
int addNode(elemtype n,list l)
{
node nod=(node)malloc(sizeof(node));
nod->n=n;
nod->next=l->header->next;
l->tail->next=nod;
l->tail=nod;
return 1;
}
void printlist(list l)
{
node p=l->header->next;
do{
printf("\n%d",p->n);
p=p->next;
}
while (p!=l->header->next) ;
}
//注这里是删除NODE下一个节点
void delNextNode(node n,list l)
{
//如果是最后一个元素 就需要考虑到链表头的指向
if (isLast(n,l)) {

node tmp=n->next;
n->next=tmp->next;
//把头结点指向新的元素
l->header->next=n->next;
free(tmp);
}
else
{
node tmp=n->next;
n->next=tmp->next;
free(tmp);
}

}

//判断是否为最后一个元素
bool isLast(node n,list l)
{
if (n->next==l->header->next) {
return true;
}
return false;
}
//JOsephus问题 还未解决这个问题,调用会报错
void Josephus(int M,int N)
{
list l=creatList();
for(int i=1;i<=N;i++)
{
addNode(i,l);
}
//开始转圈删除
while (l->header->next!=NULL) {
node p=l->header;
for(int i=0;i<M;i++)
{
p=p->next;
}
printf("%d   ",p->n);
delNextNode(p,l);
}

}
//非递归查找特定元素
node find(int x,list l)
{
node p=l->header->next;
do{
if (p->n=x) {
return p;
}
p=p->next;
}
while (p!=l->header->next) ;
return NULL;
}
//递归查找特定元素实现
node deguiFind(int x,node p,list l)
{
if(x==p->n)
{
return p;
}
else if(p==l->tail)
{
return NULL;
}
else

{
return deguiFind(x,p->next,l);
}
}
//非递归翻转单链表
void reverse(list l)
{

}
//基数排序
void sort(int *n)
{
list l[10];
//初始化每一个表
for(int i=0;i<10;i++)
{
l[i]=creatList();
}
//按照各位优先排序 这里需要提前知道应该分为多少趟
for(int j=0;j<3;j++)
{
//从最低位到最高位提取数据
while (n)
{
addNode(n,l[n%10]);
}

}

}
int main()
{
list l=creatList();
for(int i=1;i<=10000;i++)
{
addNode(i,l);
}
//////////////////////////////////////////////////////////////////////////
//查找测试
node p=l->header->next;
node fdp=deguiFind(6,p,l);
if (fdp==NULL) {
printf("没有找到");
}
else
{
printf("%d",fdp->n);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//基数排序
sort();
getchar();
return 0;
}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐