Ejemplo n.º 1
0
void CList::DelRandNode(UINT id)
{
	CCar* cur = pFirst;
	if(id == 1)	//if we want delete first element
	{
		pFirst = pFirst->pNext;
		DelNode(cur);
		cout<<"\nSuccessful delete!\n";
		return;
	}

	CCar* prev = pFirst;
	UINT i = 1;
	do
	{
		if(id == (i + 1))
		{
			cur = cur->pNext;
			prev->pNext = cur->pNext;
			DelNode(cur);
			cout<<"\nSuccessful delete!\n";
			return;
		}

		cur = cur->pNext;
		prev = cur;
		i++;
	}while(cur);

	cout<<"\nError!!! Bad index!\n";
}
Ejemplo n.º 2
0
void GenTestCase(int no)
{
  Node *n1, *n2;
  unsigned v0;
  printf("void test%d(void)\n{\n", no);
  printf("  printf(\"-- Test %d (seed: %u) --\\n\");\n", no, mySeed);
  printf("  {\n");
  printf("    int failed = 0;\n");
  ReInit();
  n1 = GenCommaExpr();
  PrintDecls(n1);
  printf("    unsigned v0 = (");
  PrintExpr(n1);
  printf(");\n");
  n2 = DupExpr(n1);
  v0 = Eval(n2);
  CheckVars(n2);
  printf("    if (v0 != %uu) ", v0);
  printf("{ failed = 1; printf(\"v0 != %uu\\n\"); }\n", v0);
  printf("    if (failed)\n      printf(\"Test %d failed\\n\");\n", no);
  printf("    errors += failed;\n");
  printf("  }\n");
  printf("  printf(\"\\n\");\n");
  printf("}\n\n");
  DelNode(n1);
  DelNode(n2);
}
Ejemplo n.º 3
0
void DelNode(Node* n)
{
  if (!n) return;
  DelNode(n->child[2]);
  DelNode(n->child[0]);
  DelNode(n->child[1]);
  free(n);
}
Ejemplo n.º 4
0
//删除结点指令
bool TCPWorker::OnNodeDel(mdk::STNetHost &host, bsp::BStruct &msg)
{
	if ( !msg["hostID"].IsValid() || sizeof(int) != msg["hostID"].m_size ) return false;
	int hostID = msg["hostID"];
	NodeList::iterator it = m_nodes.find( host.ID() );
	char *errReason = NULL;
	if ( it != m_nodes.end() ) errReason = DelNode(it->second);
	else if ( m_db.host.ID() == host.ID() )  errReason = DelNode(&m_db);
	else if (m_master.host.ID() == host.ID())errReason = DelNode(&m_master);
	ReplyUserResult(host, msg, errReason);
	return true;
}
Ejemplo n.º 5
0
CList::~CList()
{
	CCar* cur = pFirst;
	if(!bNeat)
	{
		while(cur)
		{
			pFirst = pFirst->pNext;
			DelNode(cur);
			cur = pFirst;
		}
	}
	else
	{
		CCar* pBegin = pFirst;
		while(cur)
		{
			pFirst = pFirst->pNext;
			if(cur->pSurName)
			{
				delete[] cur->pSurName;
			}
			cur = pFirst;
		}
		delete[] pBegin;
	}
}
Ejemplo n.º 6
0
void CList::Delete(void)
{
	if(!pFirst)
	{
		cout<<"\nNo available elements in list!\n";
		return;
	}
	cout<<"\nEnter index: ";
	UINT id;
	cin>>id;
	if(!cin.good() || id < 1)
	{
		cout<<"\nError!!! Bad index!\n";
		return;
	}
	if(GetCount() == 1 && id == 1)
	{
		DelNode(pFirst);
		pFirst = nullptr;
		cout<<"\nSuccessful delete!\n";
		bNeat = false;
		return;
	}

	if(bNeat)
	{
		this->DelNeatNode(id);
	}
	else
	{
		this->DelRandNode(id);
	}
}
void DelNode(PNode *Head, PNode node){
	if (!node || !Head)
		return;
	PNode y = NULL;
	PNode x = NULL;
	if (!node->left || !node->right)
		y = node;
	else
		y = Next(node);
	if (y->left)
		x = y->left;
	else
		x = y->right;
	if (x)
		x->parent = y->parent;
	if (y == y->parent->left){
		y->parent->left = x;
	}
	else
		y->parent->right = x;
	if (y != node){
		node->data = y->data;
		DelNode(Head, y);
	}
	free(y);
}
Ejemplo n.º 8
0
int CRingList::Delete()
{
	int nRet = -1;
	pthread_mutex_lock( &m_MutexList );
	nRet = DelNode();
	pthread_mutex_unlock( &m_MutexList );
	return nRet;    
}
Ejemplo n.º 9
0
BstNode<KEY, VALUE>* AvlTree<KEY, VALUE>::DelNode(const KEY& deletekey, BstNode<KEY, VALUE>* tree)
{
  BstNode<KEY, VALUE>* retp;                        // returned pointer to delete.

  if (tree == NULL)                     // Quit if searching empty tree.
    return NULL;

  if (tree -> key > deletekey)          // See if node to delete is in one
  {                                     // one of the subtrees.
    tree->left = DelNode(deletekey, tree->left);
    return Rebalance(tree);
  }
  else if (tree -> key < deletekey)
  {
    tree->right = DelNode(deletekey, tree->right);
    return Rebalance(tree);
  }

  if (tree->right && tree->left)
  {
    retp = tree;
    tree = RmHasBoth(tree);
  }
  else if (tree->left)
  {
    retp = tree;
    tree = retp->left;
  }
  else if (tree->right)
  {
    retp = tree;
    tree = retp->right;
  }
  else
  {
    retp = tree;
    tree = NULL;
  }

  if (retp)
    delete retp;

  return tree;
}
Ejemplo n.º 10
0
int
GetCacheNode(CMiniCache *cache, CMiniCacheNode **pNode)
{
  pthread_mutex_lock(&cache->lock);

  //检查当前内存使用情况
  while(cache->m_pHead && cache->lDataSize > cache->m_lMaxDataSize)
    DelNode(cache, cache->m_pHead, 1);

  if(cache->m_pIdleNode) {
    //在空闲节点链表中获取
    *pNode = GetCacheNodeFromIdleList(cache);
    pthread_mutex_unlock(&cache->lock);
    return 0;
  } else {
    if(cache->m_lNowDataPos>=cache->m_lOneAllocNum) {
      //当前块已分配完
      cache->m_lNowAllocPos++;
      if(cache->m_lNowAllocPos >= cache->m_lAlloc) {
	//已超过设定的最大可用节点数
	DelNode(cache, cache->m_pHead, 1);
	*pNode = GetCacheNodeFromIdleList(cache);
	pthread_mutex_unlock(&cache->lock);
	return 0;
      }
      cache->m_ppNode[cache->m_lNowAllocPos] = calloc(cache->m_lOneAllocNum, sizeof(CMiniCacheNode));
      if(!cache->m_ppNode[cache->m_lNowAllocPos]) {
	//操作系统暂无内存可用
	cache->m_lLastErrorCode = PROJECTBASEERRORCODE_MINICACHE+42;
	DelNode(cache, cache->m_pHead, 1);
	*pNode = GetCacheNodeFromIdleList(cache);
	cache->m_lNowAllocPos--;
	pthread_mutex_unlock(&cache->lock);
	return 0;
      }
      cache->m_lNowDataPos = 0;
    }
    *pNode = &cache->m_ppNode[cache->m_lNowAllocPos][cache->m_lNowDataPos++];
  }
  memset(*pNode,0,sizeof(CMiniCacheNode));
  pthread_mutex_unlock(&cache->lock);
  return 0;
}
Ejemplo n.º 11
0
/**************************************************************************
	//Function:			DelData
	//Description:		根据关键字删除一条记录
	//Calls:
	//Called by:
	//Input:
						tKey				记录关键字
	//Output:
	//Return:
						返回值				说明
						0					成功
						负值				失败
	//Others:
	//Author:	fanyh	Email: [email protected]
	//Date:		2008-06-16
	**************************************************************************/
int
DelData(CMiniCache *cache, map_key_t tKey)
{
  pthread_mutex_lock(&cache->lock);

  CMiniCacheNode *pOldNode = NULL;
  if(0==FindNode(cache, tKey, &pOldNode)) {
    DelNode(cache, pOldNode, 1);
  }

  pthread_mutex_unlock(&cache->lock);
  return 0;
}
Ejemplo n.º 12
0
int main()
{

    int choice, i,key;
    printf("Creation of B tree for node %d\n",M);
    while(1)
    {
        printf("1.Insert\n");
        printf("2.Delete\n");
        printf("3.Search\n");
        printf("4.Display\n");
        printf("5.Quit\n");
        printf("Enter your choice : ");
        scanf("%d",&choice);

        switch(choice)
        {
        case 1:
            //printf("Enter the key : ");
            //scanf("%d",&key);
            for(i=0; i<20; i++)
            {
                key = input_array[i];
                insert(key);
            }
            //insert(key++);
            //insert(key);
            break;
        case 2:
            printf("Enter the key : ");
            scanf("%d",&key);
            DelNode(key);
            break;
        case 3:
            printf("Enter the key : ");
            scanf("%d",&key);
            search(key);
            break;
        case 4:
            printf("Btree is :\n");
            display(root,0);
            break;
        case 5:
            exit(1);
        default:
            printf("Wrong choice\n");
            break;
        }/*End of switch*/
    }/*End of while*/
    return 0;
}/*End of main()*/
Ejemplo n.º 13
0
char* TCPWorker::OnCommand(vector<string> *cmd)
{
	if ( NULL == m_guide ) return "unconnected with guide";
	vector<string> &argv = *cmd;
	bool bLegal = false;
	if ( "shownet" == argv[0] ) bLegal = ShowNet(argv);
	else if ( "piece" == argv[0] ) bLegal = StartPiece(argv);
	else if ( "delnode" == argv[0] ) bLegal = DelNode(argv);
	else return "Invalid command";
	if ( !bLegal ) return "Error param count";

	m_reply.Wait();
	
	return NULL;
}
Ejemplo n.º 14
0
/**************************************************************************
	//Function:			AddNode
	//Description:		新加入一个节点
	//Calls:
	//Called by:
	//Input:
						pNode				指向加入节点的指针
	//Output:
	//Return:
						返回值				说明
						0					成功
						负值				失败
	//Others:
	//Author:	fanyh	Email: [email protected]
	//Date:		2008-06-16
	**************************************************************************/
int
AddNode(CMiniCache *cache, CMiniCacheNode *pNode)
{
  pthread_mutex_lock(&cache->lock);

  CMiniCacheNode *pOldNode;
  if(0==FindNode(cache, pNode->tKey, &pOldNode)) {
    DelNode(cache, pOldNode, 1);
  }
  __AddNode(cache, pNode, false);

  pthread_mutex_unlock(&cache->lock);

  return 0;
}
Ejemplo n.º 15
0
void TWgtNet::DelMinWgtNodes(const double MinWgt) {
  printf("Deleting Min Wgt %g nodes\n", MinWgt);
  printf("  (%d,%d)  -->", GetNodes(), GetEdges());
  TIntV DelNIdV;  
  for (TNodeI NI = BegNI(); NI < EndNI(); NI++) {
    double wgt = 0;
    for (int e = 0; e < NI.GetOutDeg(); e++) { 
      wgt += NI.GetOutEDat(e);
    }
    if (wgt < MinWgt) { DelNIdV.Add(NI.GetId()); }
  }
  for (int d = 0; d < DelNIdV.Len(); d++) {
    DelNode(DelNIdV[d]);
  }
  printf("  (%d,%d)\n", GetNodes(), GetEdges());
}
Ejemplo n.º 16
0
int CRingList::Put( void *data, int len )
{
	int nRet = 0;
	pthread_mutex_lock( &m_MutexList );
	if( m_RingList.size == m_RingList.max ) nRet = DelNode();
	if( nRet == 0 )
    {
    	nRet = AddNode( data, len );
    	if( m_BlockFlag && nRet == 0 && m_RingList.size == 1 )
        {
        	pthread_cond_signal( &m_CondList );
        }
    }
	pthread_mutex_unlock( &m_MutexList );
	return nRet;
}
Ejemplo n.º 17
0
/**************************************************************************
	//Function:			SelfDelUnvalidNode
	//Description:		自淘汰失效节点
	//Calls:
	//Called by:
	//Input:
	//Output:
	//Return:
						返回值				说明
						0					成功
	//Others:
	//Author:	fanyh	Email: [email protected]
	//Date:		2008-06-19
	**************************************************************************/
int
SelfDelUnvalidNode(CMiniCache *cache)
{
  cache->m_lRunFlag = 1;
  for(;cache->m_lRunFlag;) {
   pthread_mutex_lock(&cache->lock);

    while(cache->m_pHead && cache->lDataSize > cache->m_lMaxDataSize) {
      DelNode(cache, cache->m_pHead, 1);
    }

    pthread_mutex_unlock(&cache->lock);
    usleep(10000);
  }
  return 0;
}
Ejemplo n.º 18
0
void CRusSemStructure::DeleteSAMNode(long ClauseNo, CRusSemNode& SamNode)
{
	SamNode.m_Words.clear();
	for (long i=0; i < m_Nodes.size(); i++)
		if ( IsInClause(i, ClauseNo) )
			if (m_Nodes[i].IsPrimitive() && CanBeDeleted(i))
				if  (    HasGramFetAfterColon (i, "нар") 
					&& HasRichPOS (i, PRONOUN_P)
					)

					if (GetSynRelationsCount(i) == 0)
					{
						SamNode =  m_Nodes[i];
						DelNode(i);
						break;
					}
};
Ejemplo n.º 19
0
void main()
{
	for(;;){
		switch(menu_select()){
		case 1:
		printf("create AddressList LinkedList\n");
		head=CreateList();
		break;

		case 2:
		printf("insert AddressList LinkedList\n");
		p=(ListNode *)malloc(sizeof(ListNode));
		scanf("%s%s%s%s%s",p->data.num,p->data.name,p->data.sex,p->data.phone,p->data.addr);
		InsertNode(head,p);
		break;
		case 3:
		printf("query AddressList LinkedList\n");
		p=ListFind(head);
		if(p!=NULL){
			printf("%s,%s,%s,%s,%s\n",p->data.num,p->data.name,p->data.sex,p->data.phone,p->data.addr);
		}
		else printf("not found this record\n");
		break;

		case 4:
		printf("deleate AddressList LinkedList\n");
		DelNode(head);
		break;

		case 5:
		printf("output AddressList LinkedList\n");
		PrintList(head);
		break;

		case 0:
		printf("goodbye!\n");
		return;

		defalut:
		printf("Input error,try again!\n");
		return;
		}

	}
}
Ejemplo n.º 20
0
/**************************************************************************
	//Function:			GetData
	//Description:		获取节点数据
	//Calls:
	//Called by:
	//Input:
						tKey				记录关键字
	//Output:
						vpData				关键字的数据域
						lDataSize			数据域长度
						lTime				数据域失效时间
	//Return:
						返回值				说明
						0					成功
						负值				失败
	//Others:
	//Author:	fanyh	Email: [email protected]
	//Date:		2008-06-16
	**************************************************************************/
int
GetData(CMiniCache *cache, map_key_t tKey,
        void** vpData, size_t* lDataSize)
{
  int ret = -1;
  pthread_mutex_lock(&cache->lock);

  CMiniCacheNode *pOldNode;
  if(0==FindNode(cache, tKey, &pOldNode)) {
    *vpData = pOldNode->vpData;
    *lDataSize = pOldNode->lDataSize;
    DelNode(cache, pOldNode, 0);
    __AddNode(cache, pOldNode, true);
    ret = 0;
  }

  pthread_mutex_unlock(&cache->lock);
  return ret;
}
Ejemplo n.º 21
0
ChangeQueue &ChangeQueue::operator+=(ChangeQueue &Q) {
	assert(client==Q.client);
	Layout::node_iter ni;
	Layout::graphedge_iter ei;
	for(ni = Q.insN.nodes().begin(); ni!=Q.insN.nodes().end(); ++ni)
		InsNode(*ni);
	for(ei = Q.insE.edges().begin(); ei!=Q.insE.edges().end(); ++ei)
		InsEdge(*ei);
	for(ni = Q.modN.nodes().begin(); ni!=Q.modN.nodes().end(); ++ni)
		ModNode(*ni,igd<Update>(*ni));
	for(ei = Q.modE.edges().begin(); ei!=Q.modE.edges().end(); ++ei)
		ModEdge(*ei,igd<Update>(*ei));
	for(ni = Q.delN.nodes().begin(); ni!=Q.delN.nodes().end(); ++ni)
		DelNode(*ni);
	for(ei = Q.delE.edges().begin(); ei!=Q.delE.edges().end(); ++ei)
		DelEdge(*ei);
	GraphUpdateFlags() |= Q.GraphUpdateFlags();
	return *this;
}
Ejemplo n.º 22
0
//响应结点退出请求
bool TCPWorker::OnNodeExit(mdk::STNetHost &host)
{
	Exist *pExist = NULL;
	if ( m_db.host.ID() == host.ID() ) //数据库退出
	{
		pExist = &m_db;
		DBExit();
	}
	else if ( m_master.host.ID() == host.ID() ) //主分片退出
	{
		pExist = &m_master;
		pExist->status = NodeStatus::NotOnline;
	}
	else//结点退出
	{
		NodeList::iterator it = m_nodes.find( host.ID() );
		if ( it == m_nodes.end() ) return false;
		pExist = it->second;
		pExist->status = NodeStatus::Idle;
	}
	DelNode(pExist);
	return true;
}
Ejemplo n.º 23
0
int CRingList::Pop( void *data , int *len  )
{
	int nRet = -1;
	pthread_mutex_lock( &m_MutexList );
	if ( m_RingList.size > 0 )
    {
    	char *dataPtr = (char *)(m_RingList.front->data);
    	int dataLen = m_RingList.front->len;
    	if ( data != NULL ) memcpy( (char *)data, dataPtr, dataLen );
    	if ( len != NULL ) *len = dataLen;
    	nRet = 0;
    }
	else if ( m_BlockFlag )
    {
    	pthread_cond_wait( &m_CondList, &m_MutexList );
    }
	if ( nRet == 0 ) 
    {
    	DelNode();
    }
	pthread_mutex_unlock( &m_MutexList );
	return nRet;
}
Ejemplo n.º 24
0
void BK(int64_t *Graph, int64_t *R, int64_t *P, int64_t *X )
{
	if(0 == P[0] && 0 == X[0])
	{
//		printf("get clique:\n");
		int j ;
		printf("%lld:",USER);
		for(j=0;R[j] !=0 ; ++j)
		{
			printf("%lld\t",R[j]);
		}
		printf("\n");
	}
	else if(0==P[0]) 
	{
	}
	else
	{
	int i=0;
	int64_t  P_copy[LINE]={0};
	CopyArray(P,P_copy);
	while(P[i] != 0)
	{
		int64_t R_1[LINE]={0}, P_1[LINE]={0}, X_1[LINE] = {0};
		CopyArray(R,R_1);
		AddNode(R_1,P[i]);
		int pos=Find(Graph,P[i]);
		Insect(P_copy,Graph+pos*SHARE+1,P_1);
		Insect(X,Graph+pos*SHARE+1,X_1);
		BK(Graph,R_1,P_1,X_1);
		DelNode(P_copy,P[i]);
		AddNode(X,P[i]);
		++i;
	}
	}
}
Ejemplo n.º 25
0
void    key_SetGroups(void)
{
  if (bKey == bKEY_ENTER)
  {    
    if (enKeyboard == KBD_ENTER)        
    {                                   // первое нажатие кнопки '¬вод'
      enKeyboard = KBD_INPUT2;          // подготовка к вводу номера группы
      ShowHi(szGroups); 
      Group();

      boSetGroups = true;
      SaveCache(&chSetGroups);
    }
    else if (enKeyboard == KBD_INPUT2)  // номер группы не введЄн
    {                                   // начинаем с первой группы
      enKeyboard = KBD_POSTINPUT3;      
      ibX = 0;                          // индекс группы
      ShowGroupNumber();  
    }
    else if (enKeyboard == KBD_POSTINPUT2)
    {                                   
      if ((ibX = GetCharLo(10,11)-1) < bGROUPS)
      {                                 // получили индекс группы
        enKeyboard = KBD_POSTINPUT3;
        ShowGroupNumber();
      } 
      else Beep();
    }    
    else if (enKeyboard == KBD_POSTINPUT1)              
    {                                   // запись данных после ввода
      if ((noT.ibCanal = GetCharLo(6,8)-1) < bCANALS)
      {
        enKeyboard = KBD_POSTENTER;     

        if (szLo[4] == '-')
          noT.ibCanal |= 0x80;

        if (AddNode() == 1)             // добавление узла в группу
        {                               // нет такого узла
          if (++ibY == bCANALS)      // если группа заполнена полностью
          {
            enKeyboard = KBD_SHOW;      // переходим в режим просмотра
            ibY = 0;
          }
        }
        else Beep();                    // есть такой узел
      }
      else Beep();
    }                                                                
    else if (enKeyboard == KBD_SHOW)
    {                                   // продолжаем просмотр
      ibY++;                            // переходим на следующий узел
      if (ibY == GetGroupsSize(ibX))    // дошли до последнего узла
      {                                 
        if (GetGroupsSize(ibX) == bCANALS) 
          ibY = 0;                      // если полный список - продолжаем просмотр с начала
        else 
          enKeyboard = KBD_POSTENTER;   // иначе ввод нового узла
      }
    }


    if (enKeyboard == KBD_POSTINPUT3)
    {
      // при перепрограммировании разрешаетс¤ редактировать незаданные группы
      if ((enGlobal == GLB_REPROGRAM) && (mpfUsedGroups[ibX] == true))
      {
        Error();
        LongBeep();
        return;
      }
    }


    if ((enKeyboard == KBD_POSTINPUT3) || (enKeyboard == KBD_INPUT1))
    {                                   // начинаем просмотр группы с начала
      ibY = 0;                          // переход на первый узел
      if (GetGroupsSize(ibX) == 0) 
        enKeyboard = KBD_POSTENTER;     // если группа пуста¤ - режим ввода
      else                  
        enKeyboard = KBD_SHOW;          // есть группа не пуста¤ - режим просмотра
    }


    if (enKeyboard == KBD_POSTENTER)    // неповредственно подготовка ввода
    {
      enKeyboard = KBD_INPUT1; 
      ShowLo(szMaskGroups);
    }
    else if (enKeyboard == KBD_SHOW)    // непосредственно просмотр
      ShowGroup();     
  }


  else if (bKey < 10)
  {
    if ((enKeyboard == KBD_INPUT2) || (enKeyboard == KBD_POSTINPUT2))
    {
      enKeyboard = KBD_POSTINPUT2;
      ShiftLo(10,11);
    }
    else 
    if ((enKeyboard == KBD_INPUT1) || (enKeyboard == KBD_POSTINPUT1))
    {
      enKeyboard = KBD_POSTINPUT1;
      ShiftLo(6,8);
    }
  }


  else if (bKey == bKEY_MINUS)
  {    
    if (enKeyboard == KBD_SHOW)         
    {                                   // в режиме просмотра
      DelNode();                        // удалить узел из группы
      LongBeep();

      if (GetGroupsSize(ibX) == 0)
      {
        enKeyboard = KBD_INPUT1; 
        ShowLo(szMaskGroups);
      }
      else ShowGroup();
    }
 

    else if ((enKeyboard == KBD_INPUT1) || (enKeyboard == KBD_POSTINPUT1)) 
    {                                   // в режиме ввода
      if (szLo[4] == '-')               // изменить знак узла на противоположный
        szLo[4] = '+';
      else
        szLo[4] = '-';
    } 
    else Beep();
  }


  else if (bKey == bKEY_POINT)
  {
    if ((enKeyboard == KBD_POSTENTER) || 
        (enKeyboard == KBD_INPUT1)    || (enKeyboard == KBD_SHOW))
    {
      if (++ibX >= bGROUPS)
        ibX = 0;

      ShowGroupNumber();
      ibY = 0;                

      if (GetGroupsSize(ibX) == 0) 
      {
        enKeyboard = KBD_INPUT1;        // если группа пуста¤ - режим ввода
        ShowLo(szMaskGroups);
      }
      else                  
      {
        enKeyboard = KBD_SHOW;          // есть группа не пуста¤ - режим просмотра
        ShowGroup();
      }
    }
    else Beep();
  }
}
Ejemplo n.º 26
0
int main()
{
  listPtr List, Queue, Stack, Splay;
  char *String1, *String2, *String3, *String4, *Get;
  int Result;

  printf("Testing LINKLIST Library for ANSI C.\n\n");

  String1 = malloc(20);
  String2 = malloc(20);
  String3 = malloc(20);
  String4 = malloc(20);
  strcpy(String1, "Hi");
  strcpy(String2, "Low");
  strcpy(String3, "Up");
  strcpy(String4, "Down");

  printf("Creating List.\n");
  List = NewListAlloc(LIST, DMALLOC, DFREE, (NodeCompareFunc)strcmp);
  printf("Creating Queue.\n");
  Queue = NewListAlloc(QUEUE, DMALLOC, DFREE, NULL);
  printf("Creating Stack.\n");
  Stack = NewListAlloc(STACK, DMALLOC, DFREE, NULL);
  printf("Creating Splay Tree\n");
  Splay = NewListAlloc(STREE, DMALLOC, DFREE, (NodeCompareFunc)StringCompare);

  printf("Adding Elements to List...\n");
  AddNode(List, NewNode("Hi"));
  AddNode(List, NewNode("Low"));
  AddNode(List, NewNode("Up"));
  AddNode(List, NewNode("Down"));

  printf("Adding Elements to Queue...\n");
  AddNode(Queue, NewNode("Hi"));
  AddNode(Queue, NewNode("Low"));
  AddNode(Queue, NewNode("Up"));
  AddNode(Queue, NewNode("Down"));

  printf("Adding Elements to Stack...\n");
  AddNode(Stack, NewNode(String1));
  AddNode(Stack, NewNode(String2));
  AddNode(Stack, NewNode(String3));
  AddNode(Stack, NewNode(String4));

  printf("Adding Elements to Splay Tree...\n");
  AddNode(Splay, NewNode("High"));
  AddNode(Splay, NewNode("Low"));
  AddNode(Splay, NewNode("Up"));
  AddNode(Splay, NewNode("Down"));

  printf("Attempting to add duplicate nodes to Splay Tree...\n");
  Result = AddNode(Splay, NewNode("Down"));
  printf("Result: ");
  if (Result == LLIST_OK)
    printf("OK\n");
  else if (Result == LLIST_BADVALUE)
    printf("Node Already Exists; not added\n");
  else printf("Error\n");

  printf("Calimed Memory: %d bytes\n", DCOUNT(NULL));

  printf("LIST:\n");
  PrintList(List, "%s");
  printf("QUEUE:\n");
  PrintList(Queue, "%s");
  printf("STACK:\n");
  PrintList(Stack, "%s");
  printf("SPLAY:\n");
  PrintList(Splay, "%s");
  
  printf("\n-----------------------\n");

  printf("Reading Element from LIST\n");
  printf("Read Element: %s\n", GetNode(List));
  PrintList(List, "%s");

  printf("\n\nReading Element from QUEUE\n");
  printf("Read Element: %s\n", GetNode(Queue));
  PrintList(Queue, "%s");

  printf("\n\nReading Element from STACK\n");
  printf("Read Element: %s\n", (Get = GetNode(Stack)));
  DFREE(Get);
  PrintList(Stack, "%s");

  printf("\n-----------------------\n");

  printf("Reading Element #2 from LIST\n");
  printf("Read Element: %s\n", IndexNode(List, 2));
  PrintList(List, "%s");

  printf("\nAdding One More Element to LIST\n");
  AddNode(List, NewNode("And"));
  PrintList(List, "%s");

  printf("\n-----------------------\n");

  printf("\nSorting LIST\n");
  SortList(List);
  PrintList(List, "%s");

  printf("\n-----------------------\n");
  
  printf("\nDeleting Element 2 From LIST\n");
  IndexNode(List, 2);
  RemoveList(List);
  PrintList(List, "%s");

  printf("\nDeleting Head From LIST\n");
  DelHeadList(List);
  PrintList(List, "%s");

  printf("\nDeleting Tail From LIST\n");
  DelTailList(List);
  PrintList(List, "%s");

  printf("\n------------------------\n");
  
  printf("Reading Element from Splay Tree\n");
  printf("Read Element: %s\n", GetNode(Splay));

  printf("\nDeleting Element From Splay Tree\n");
  DelNode(Splay);
  PrintList(Splay, "%s");

  printf("\nDeleting Element \"Low\" In Splay Tree\n");
  FindNode(Splay, "Low");
  DelNode(Splay);
  PrintList(Splay, "%s");

  printf("Reading Element from Splay Tree\n");
  printf("Read Element: %s\n", GetNode(Splay));

  printf("\n-----------------------\n");

  printf("Removing List.\n");
  FreeList(List, NULL);
  printf("Removing Queue.\n");
  FreeList(Queue, NULL);
  printf("Removing Stack.\n");
  FreeList(Stack, NULL);
  printf("Removing Splay Tree.\n");
  FreeList(Splay, NULL);

  printf("\n-----------------------\n");
  
  printf("\nUnclaimed Memory: %d bytes\n", DCOUNT(NULL));

  printf("\nLinkList Test/Demo Done.\n");

  return 0;
} /* main */
Ejemplo n.º 27
0
int main(void) {

    CircleList *L1 = (CircleList *)malloc(sizeof(CircleList));
    ListInit(L1);
    int choice;
    int data;

    system("clear");
    while(TRUE) {

        while(TRUE) {
            printf("Select Menu\n");
            printf("0 : Clear screen ");
            printf("1 : Add on head ");
            printf("2 : Add on tail ");
            printf("3 : Show First data ");
            printf("4 : Show next data ");
            printf("5 : Show all data ");
            printf("6 : Delete data ");
            printf("7 : Exit\n");
            printf("select : ");
            scanf("%d", &choice);
            if(0 <= choice && choice <= 7)
                break;
        }

        switch(choice) {
        case CLEARSCREEN:
            system("clear");
            break;
        case HEADADD:
            printf("Add on head.\n");
            printf("Insert number : ");
            scanf("%d", &data);
            if(data < 1)
                break;
            HeadAdd(L1, data);
            printf("%d add completed!\n\n", data);
            break;

        case TAILADD:
            printf("Add on tail.\n");
            printf("Insert number : ");
            scanf("%d", &data);
            if(data < 1)
                break;
            TailAdd(L1, data);
            printf("%d add Completed!\n\n", data);
            break;

        case LFIRST:
            printf("Sort first data.\n");
            printf("\n%d\n\n", LFirst(L1));
            break;

        case LNEXT:
            printf("Sort next data.\n");
            printf("\n%d\n\n", LNext(L1));
            break;

        case SHOWALLDATA:
            printf("\n");
            ShowAllData(L1);
            printf("\n");
            break;

        case DELNODE:
            printf("Do you want to delete? (y:1 / n:2) : ");
            scanf("%d", &choice);
            if(choice == 1)
                printf("%d deleted.\n", DelNode(L1));
            else
                printf("Cancled.\n");
            break;

        case EXIT:
            return 0;
        }
    }
}