欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

不带头结点单链表

程序员文章站 2024-03-21 12:57:34
...

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 <stdio.h>
#include <assert.h>
#include <stdlib.h>
#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("\n");
}

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 <stdio.h>

#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);
}