贺老师,您第四周实践项目里有两个项目5。。。
对于这个问题,我自己又写了一个循环双链表的小算法库(因为只实现了循环链表的一部分功能)!
代码:
main.cpp
#include<bits/stdc++.h>
#include"xunshuanglist.h"
using namespace std;
void myinsert(dlink *p,dlink *q,int n)
{
int num;
dlink *r,*t;
r=q;t=p;
while(r->next!=q)
r=r->next;
num=chang(p);
if(n==0)///OK
{
t=t->next;
p->next=q->next;
q->next->prior=q;
r->next=t;
t->prior=r;
}
else if(n>0&&n<num)
{
dlink *k,*h;
h=p;
int ji=0;
while(ji<n)
{
h=h->next;
ji++;
}
k=h->next;
h->next=q->next;
q->next->prior=h;
r->next=k;
k->prior=r;
}
else
{
dlink *s;
s=p;
while(s->next!=p)
s=s->next;
p->prior=r;
r->next=s->next;
s->next=q->next;
q->next->prior=s;
}
}
int main()
{
dlink *head1,*head2;
int num;
cin>>num;
head1=(struct node *)malloc(sizeof(struct node));
head2=(struct node *)malloc(sizeof(struct node));
creat(head1,num);
creat(head2,num);
display(head1);
display(head2);
cout<<chang(head1)<<endl;
myinsert(head1,head2,9);
display(head1);
return 0;
}
xunshuanglist.h
#ifndef XUNSHUANGLIST_H_INCLUDED
#define XUNSHUANGLIST_H_INCLUDED
typedef struct node
{
int data;
node *prior;
node *next;
}dlink;
void creat(dlink *head,int num);
void display(dlink *p);
int chang(dlink *p);
#endif // XUNSHUANGLIST_H_INCLUDED
xunshuanglist.cpp
#include"xunshuanglist.h"
#include<bits/stdc++.h>
using namespace std;
void creat(dlink *head,int num)
{
int i;
dlink *p,*r;
r=head;
for(i=0;i<num;i++)
{
p=(struct node *)malloc(sizeof(struct node));
cin>>p->data;
r->next=p;
p->prior=r;
p->next=NULL;
r=p;
}
p->next=head;
head->prior=p;
}
void display(dlink *p)
{
int w;
p=p->next;
w=p->data;
while(p->next->data!=w)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<endl;
}
int chang(dlink *p)
{
dlink *j;
int num=0;
j=p;
p=p->next;
while(p->next!=j)
{
num++;
p=p->next;
}
return num+1;
}
n等于0的时候:
n大于0且小于线性表p的长度的时候:
知识点总结:
在掌握循环双链表基础知识的基础上去修改循环双链表;指针还是很重要的一个工具呀!
心得体会:
对于数据结构的题目,画图还是很好的!