노 헤드 노드 싱글 체인 시계

2345 단어 데이터 구조
Link.h
typedef int ELEM_TYPE;

typedef struct Node
{
	ELEM_TYPE data;
	struct Node* next;
}Node,*PNode;

void Init(PNode* phead);
PNode BuyNode(ELEM_TYPE val);
bool InsertTail(PNode* phead,ELEM_TYPE val);
bool InsertHead(PNode* phead,ELEM_TYPE val);
void Show(PNode phead);
bool DeleteKey(PNode* phead,ELEM_TYPE key);
void clear(PNode* phead);

Link.cpp
#include 
#include 
#include 
#include "Link.h"

void Init(PNode* phead)
{
	if(phead == NULL)
	{
		return;
	}
	*phead = NULL;
}

PNode BuyNode(ELEM_TYPE val)
{
	PNode pnewnode = (PNode)malloc(sizeof(Node));
	if(pnewnode == NULL) exit(0);
	pnewnode->data = val;
	pnewnode->next = NULL;
	return pnewnode;
}

bool InsertTail(PNode* phead,ELEM_TYPE val)
{
	if(phead == NULL)
	{
		return false;
	}
	if(*phead == NULL)
	{
		PNode pnewnode = BuyNode(val);
		*phead = pnewnode;
		return true;
	}

	PNode pcur = *phead;
	PNode pnewnode = BuyNode(val);
	while(pcur->next != NULL)
	{
		pcur = pcur->next;
	}
	pcur->next = pnewnode;
	return true;
}

bool InsertHead(PNode* phead,ELEM_TYPE val)
{
	if(phead == NULL)
	{
		return false;
	}

	PNode pnewnode = BuyNode(val);
	pnewnode->next =*phead;
	(*phead) = pnewnode;
	return true;
}

bool DeleteKey(PNode* phead,ELEM_TYPE key)
{
	if(phead == NULL)
	{
		return false;
	}
	PNode pfront = *phead;
	while(pfront->next != NULL)
	{
		if(pfront->next->data == key)
		{
			break;
		}
		pfront = pfront->next;
	}
	if(pfront->next == NULL)
	{
		return false;
	}

	PNode pcur = pfront->next;
	pfront->next = pcur->next;
	free(pcur);
	return true;
}

void Show(PNode phead)
{
	PNode pcur = phead->next;
	while(pcur->next != NULL)
	{
		printf("%d ",pcur->data);
		pcur = pcur->next;
	}
	printf("
"); } void clear(PNode* phead) { struct Node* pCur = *phead; struct Node* pNext ; while(pCur->next != NULL) { pNext = pCur->next; free(pCur); pCur = pNext; } *phead = NULL; }

main.cpp
#include 

#include "Link.h"

int main()
{
	PNode head;
	Init(&head);
	for(int i=0; i<10; i++)
	{
		InsertTail(&head,i);
	}
	DeleteKey(&head,4);
	Show(head);
	clear(&head);
}

좋은 웹페이지 즐겨찾기