带头结点的单链表的插入,删除,转置,清空,判断空,统计节点数目

//单链表  
//带头结点的单链表  
#include  
#include  
//单链表的结构体  
typedef struct _Node
{
	int data;
	struct _Node* next;
}Node, *LinkList;
void Init(LinkList* list)
{
	(*list) = (Node*)malloc(sizeof(Node));
	(*list)->next = NULL;
}
void InsertHeadList(LinkList list)
{
	int val;
	scanf("%d", &val);
	while (val != 0)
	{
		Node* node = (Node*)malloc(sizeof(Node));
		node->data = val;
		node->next = list->next;
		list->next = node;
		scanf("%d", &val);
	}
}
void PrintList(LinkList list)
{
	Node* r;
	r = list->next;
	while (r != NULL)
	{
		printf("%d ", r->data);
		r = r->next;
	}
	printf("\n");
}
void InsertTailList(LinkList list)
{
	int val;
	scanf("%d", &val);
	Node* s = list;
	while (s->next != NULL)
	{
		s = s->next;
	}
	while (val != 0)
	{
		Node* node = (Node*)malloc(sizeof(Node));
		node->data = val;
		node->next = NULL;
		s->next = node;
		s = node;
		scanf("%d", &val);
	}
}
void DeleteHeadList(LinkList list)
{
	if (list->next == NULL)
	{
		return;
	}
	Node* s = list->next;
	list->next = list->next->next;
	free(s);
}
void DeleteTailList(LinkList list)
{
	if (list->next == NULL)
	{
		return;
	}
	Node* r = list;
	while (r->next->next != NULL)
	{
		r = r->next;
	}
	Node* s = r->next;
	r->next = NULL;
	free(s);
}
void ClearList(LinkList list)
{
	while (list->next != NULL)
	{
		DeleteTailList(list);
	}
}
bool IsEmpty(LinkList list)
{
	if (list->next == NULL)
	{
		return true;
	}
	return false;
}
int nCountList(LinkList list)
{
	int num = 0;
	Node* r = list->next;
	while (r != NULL)
	{
		r = r->next;
		num++;
	}
	return num;
}
void ReverseList(LinkList list)
{
	//三指针法  
	//一个节点和空链表都是不需要逆转的  
	if (list->next == NULL || list->next->next == NULL)
	{
		return;
	}
	Node* pre;
	Node* mid;
	Node* last;
	pre = list->next;
	mid = pre->next;
	last = mid->next;
	pre->next = NULL;
	//如果有三个节点以上我们可以进入循环体进行操作  
	while (last != NULL)
	{
		//每次反转一个  
		mid->next = pre;
		//节点后移  
		pre = mid;
		mid = last;
		last = last->next;

	}
	mid->next = pre;
	list->next = mid;
}
int main(void)
{
	LinkList list;
	Init(&list);
	//单链表的插入  
	//头插  
	InsertHeadList(list);
	//尾插  
	InsertTailList(list);
	//统计节点数目  
	int nCount = nCountList(list);
	printf("nCount = %d\n", nCount);
	//单链表的删除  
	//头删  
	DeleteHeadList(list);
	//尾删  
	DeleteTailList(list);
	PrintList(list);
	//带头结点的单链表的逆序  
	ReverseList(list);
	PrintList(list);
	//清空  
	ClearList(list);
	//判断空  
	bool temp = IsEmpty(list);
	if (temp == true)
	{
		printf("空\n");
	}
	else
	{
		printf("不空\n");
	}
	return 0;
}

你可能感兴趣的:(数据结构,C语言,C++)