`
shared
  • 浏览: 3076 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

一个带头节点的链表(孙磊)

 
阅读更多

这个是我自己实现的一个带头节点的单链表:

 

#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2

typedef int Status;
typedef int ElemType;

typedef struct LNode
{
	ElemType elem;
	struct LNode* next;
}LinkList;

Status Init(LinkList* head)
{
	if(head == NULL)
	{
		return ERROR;
	}
	
	head->elem = 0;
	head->next = NULL;
	
	return OK;
}

Status Insert(LinkList* head, LinkList** curr, ElemType elem)
{
	LinkList* node = (LinkList*) malloc(sizeof(LinkList));

	if(!node)
	{
		return ERROR;
	}

	if((*curr)==NULL)
	{
		return ERROR;
	}

	node->elem = elem;
	node->next = NULL;
	
	(*curr)->next = node;
	(*curr) = node;
	
	head->elem++;
	
	return OK;
}

Status Print(LinkList* head)
{
	if(head == NULL)
	{
		return ERROR;
	}

	printf("Total %d elems\n", head->elem);
	head = head->next;
	while(head->next != NULL)
	{
		printf("%5d", head->elem);
		head = head->next;
	}
	printf("%5d\n",head->elem);
	
	return OK;
}

Status Del(LinkList* head, int index)
{
	int i = 1;
	LinkList* temp;
	if(index < 0 || index > head->elem)
	{
		return ERROR;
	}
	head->elem--;
	if(index == 1)
	{
		temp = head->next;
		head->next = head->next->next;	
	}
	else
	{
		head = head->next;
		while(i < index - 1)
		{
			head = head->next;
			i++;
		}
		temp = head->next;
		head->next = head->next->next;
	}
	free(temp);
	return OK;
}

void Free(LinkList* head)
{
	LinkList* p = head;
	while(p->next != NULL)
	{
		head = head->next;
		free(p);
		p = head;
	}
	free(p);
}

void main(void)
{
	LinkList* head = (LinkList*) malloc(sizeof(LinkList));
	LinkList* curr = head;
	if(!head)
	{
		return ERROR;
	}
	Init(head);
	Insert(head,&curr,1);
	Insert(head,&curr,2);
	Insert(head,&curr,3);
	Insert(head,&curr,4);
	Insert(head,&curr,5);
	Insert(head,&curr,6);
	Insert(head,&curr,7);
	Print(head);
	printf("\ndel 1st\n");
	Del(head,1);
	Print(head);
	printf("\ndel 2nd\n");
	Del(head,2);
	Print(head);
	printf("\ndel 3rd\n");
	Del(head,3);
	Print(head);
	Free(head);
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics