先頭ノードを持たない単一サイクルチェーンテーブル


ヘッダファイルを作成するnlist.h
#pragma once
//        ,          ,   ,    (       ),
//  :  (                    )
//            ,    next       

typedef struct NNode
{
 int data;//  
 struct NNode *next;//        
}NNode,*PNList;

//     ,     NULL,       
void InitList(PNList *pplist);

//  ,       ,       
bool Insert_head(PNList *pplist,int val);

//  ,          ,       
bool Insert_tail(PNList *pplist,int val);

// plist      key,      ,    NULL
NNode * Search(PNList plist,int key);

//  
bool IsEmpty(PNList plist);

//  plist     key,          ,       
bool DeleteVal(PNList *pplist,int key);

//      
int GetLength(PNList plist);

//      
void Show(PNList plist);

//    ,       ,       
void Clear(PNList *pplist);

//      ,       ,       
void Destroy(PNList *pplist);

nlistを作成するcppファイル
#include 
#include 
#include 
#include "nlist.h"

//     ,     NULL,       
void InitList(PNList *pplist)
{
 assert(pplist != NULL);
 if(pplist == NULL)
  return;
  
 *pplist = NULL;
}

//  ,       ,       
bool Insert_head(PNList *pplist,int val)
{
 NNode *p = (NNode *)malloc(sizeof(NNode));
 p->data = val;
 if(IsEmpty(*pplist))
 {
  p->next = p;
  *pplist = p;
 }
 else
 {
  NNode *q;//   
  for(q=*pplist;q->next!=*pplist;q=q->next);
  p->next = *pplist;
  *pplist = p;
  q->next = p;
 }
 
 return true;
}

//  ,          ,       
bool Insert_tail(PNList *pplist,int val)
{
 NNode *p = (NNode *)malloc(sizeof(NNode));
 p->data = val;
 if(IsEmpty(*pplist))
 {
  p->next = p;
  *pplist = p;
 }
 else
 {
  NNode *q;//   
  for(q=*pplist;q->next!=*pplist;q=q->next);
  q->next=p;
  p->next=*pplist;
 }
 
 return true;
}

// plist      key,      ,    NULL
NNode * Search(PNList plist,int key)
{
 NNode *q;
 for(q=plist;q->next!=plist;q=q->next)
 {
  if(q->data==key)
  {
   return q;
  }
 }
 if(q->data==key)
 {
  return q;
 }
 
 return NULL;
}

//  ,  plist   NULL
bool IsEmpty(PNList plist)
{
 return plist == NULL;
}

//  plist     key,          ,       
bool DeleteVal(PNList *pplist,int key)
{
 if(IsEmpty(*pplist))
 {
  return false;
 }
 NNode *p;
 NNode *q;
 for(q=*pplist;q->next!=*pplist;q=q->next)
 {
  if(q->next->data==key)
  {
   p=q->next;
   q->next=q->next->next;
   free(p);
   
   return true;
  }
 }
 
 p=*pplist;
 if(p->data==key)
 {
  *pplist=p->next;
  q->next=*pplist;
  free(p);
  
  return true;
 }
 
 return false;
}

//      
int GetLength(PNList plist)
{
 int count=1;
 for(NNode *q=plist;q->next!=plist;q=q->next)
 {
  count++;
 }
 return count;
}

//      
void Show(PNList plist)
{
 if(IsEmpty(plist))
  return ;
 NNode *p=plist;
 for(;p->next!=plist;p=p->next)//bug
 {
  printf("%d ",p->data);
 }
 printf("%d 
"
,p->data); } // , , void Clear(PNList *pplist) { *pplist=NULL; } // , , void Destroy(PNList *pplist) { NNode *p; NNode *q=*pplist; while(q->next!=*pplist) { p=q->next; q->next=p->next; free(p); } *pplist=NULL; }