雙循環鏈表的相關算法

#include<iostream>
#include<malloc.h>
using namespace std;


typedef int elemtype;
typedef struct node
{
 elemtype data;
 struct node *left,*next;
}nodetype;


nodetype *create()
{
 cout<<"創建一個雙循環鏈表"<<endl;
 nodetype *head,*p,*s;
 p=(nodetype *)malloc(sizeof(nodetype));
 head=p;
 s=p;
 s->next=NULL;
 elemtype n;
 while(cin>>n &&n!=0)
 {
  p=(nodetype *)malloc(sizeof(nodetype));
  p->data=n;
  s->next=p;
  p->left=s;
  s=s->next;
  s->next=head;
 }
 return head;
}


void dis(nodetype *head)
{
 nodetype *p=head->next;
 if(p==NULL)
 {
  cout<<"空表"<<endl;
  return;
 }
 while(p!=head)
 {
  cout<<p->data<<" ";
  p=p->next;
 }
 cout<<endl;
}

 

int len(nodetype *head)
{
 nodetype *p=head->next;
 if(p==NULL)
 {
  return 0;
 }
 int i=0;
 while(p!=head)
 {
  i++;
  p=p->next;
 }
 return i;
}

 

nodetype *ins(nodetype *head,int i,elemtype x)
{
 int j=len(head);
 if(i<1 ||i>j+1)
 {
  cout<<"i不合格"<<endl;
  return head;
 }
 nodetype *p,*q,*s;
 q=(nodetype *)malloc(sizeof(nodetype));
 q->data=x;
 p=head->next;
 s=head;
 for(j=1;j<i;j++)
 {
  s=p;
  p=p->next;
 }
 q->next=p;
 q->left=s;
 s->next=q;
 p->left=q;
 return head;
}

 

nodetype *del(nodetype *head,int i)
{
 int j=len(head);
 if(i<1||i>j)
 {
  cout<<"i不合格"<<endl;
  return head;
 }
 if(j==1)
 {
  head->next=NULL;
  return head;
 }
 nodetype *p,*s,*q;
 p=head->next;
 s=head;
 for(j=1;j<i;j++)
 {
  s=p;
  p=p->next;
 }
 q=p->next;
 s->next=q;
 q->left=s;
 return head;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章