算法思想:指针扫描链表,遇到偶数位的先保存此节点,然后删除,再然后把此节点插入到另外一个链表中,最后进行连接即可,基本的插入删除操作,这个程序我写得还有bug:只能对偶数个数字进行重新排序,对奇数的要修改q指针把q->next!=NULL改为q!=NULL
#include<stdio.h>
#include<stdlib.h>
typedef struct student
{
int data
struct student *next
struct student *pre
}dnode
dnode *create()
{
int n=8
dnode *head,*p,*q
head=(dnode *)malloc(sizeof(dnode))
p=head
while(n)
{
int x
printf("enter the num:\n")
scanf("%d",&x)
q=(dnode *)malloc(sizeof(dnode))
q->data=x
p->next=q
q->pre=p
p=q
n--
}
head=head->next
head->pre=NULL
p->next=NULL
return head
}
dnode *New_sort(dnode *head)
{
dnode *head2,*p,*q,*s,*n //head2保存偶数节点
p=head
head2=(dnode *)malloc(sizeof(dnode))
head2->next=NULL
while(1)
{
q=p->next
if(q->next!=NULL)
{
s=(dnode *)malloc(sizeof(dnode))
s->data=q->data //保存偶数节点到head2中
q->next->pre=q->pre //删除偶数节点head1
q->pre->next=q->next
free(q)
if(head2->next==NULL)
{
head2->next=s
s->pre=head2
s->next=NULL
}
else
{
n=(dnode *)malloc(sizeof(dnode))
n=head2->next
s->pre=head2 //插入head2节点
s->next=head2->next
head2->next->pre=s
head2->next=s
}
}
else break
if(p->next!=NULL)
{
p=p->next
}
else break
}
while(p->next!=NULL)p=p->next
head2=head2->next //head和head2连接
p->next=head2
head2->pre=p
return head
}
void prinf(dnode *head)
{
dnode *p
p=head
while(p!=NULL)
{
printf("%3d",p->data)
p=p->next
}
printf("\n")
}
void main()
{
dnode *head
head=create()
prinf(head)
head=New_sort(head)
prinf(head)
}
可以用结构体和指针来实现
定义:
定义一个单个元素的结构
typedef struct Chain_tag { // 这里用typedef来定义,方便使用int data // 这里的数据可以是任意类型
//其他数据
struct Chain_tag *prev, *next// 由于Chain为不完全类型,故只能用指针的方式声明
} Chain
使用:
用单个结构体的指针作为head
#include <malloc.h>//Chain的定义写在这里
Chain *
alloc_single_chain(int data /*, (其他参数)*/)
{
Chain *tmp
tmp = malloc(sizeof(Chain))
tmp.data = data
//...其余数据初始化
tmp.prev = tmp.next = NULL // 将前后指针置为NULL
return tmp
}
void
dispose_chain(Chain *target) //其实这里功能简单,用宏实现也可以
{
free(target)
return
}
int main()
{
Chain *head
Chain *pos
head = alloc_single_chain(10)//初始化起始结点
head->next = alloc_single_chain(11)//同理。。下一个结点
for (pos = head pos pos = pos->next)//清理垃圾好习惯
{
dispose_chain(pos)
}
return 0
}
这里有几点要注意:
由于链表用指针来实现,故不要忘记分配内存
垃圾清理时一定要从起始结点开始依次向后释放,以防内存泄漏
前面创建的双向循环链表没有问题clock变量是什么意思,uclock是什么意思,等等
感觉你的代码思路有点乱,漏洞很多,能不能注释一下你的代码,编写代码习惯不太好
约瑟夫环的游戏的具体要求是什么