其他分享
首页 > 其他分享> > 链表之单循环链表

链表之单循环链表

作者:互联网

单链表之单循环链表

单向循环链表的关键所在是最后一个节点的next存储了头节点的地址,这是对单向循环链表的操作关键所在
接下来我将实现增、删、改、查这四项最基本的操作,剩下你想要什么操作自己可以根据对链表的理解添加对应的数据操作

后面main函数里是对代码的测试


//单向循环链表

//定义链表节点
typedef struct Node{

	int data;
	Node* next;
}Node;
Node * createList()
{
	Node* headNode = (Node*)malloc(sizeof(Node));
	headNode->next = NULL;
	return headNode;
}
//创建节点
Node* createNode(int data)
{
	Node * newNode = (Node*)malloc(sizeof(Node));
	newNode->data = data;
	newNode->next = NULL;
	return newNode;
}
//增加节点
void addNode(Node * headNode, int data)
{
	Node * newNode = createNode(data);
	if (headNode->next == NULL)
	{
		headNode->next = newNode;
		newNode->next = headNode;
	}
	else
	{
		newNode->next = headNode->next;
		headNode->next = newNode;
	}
}
//删除节点
void deleteNode(Node * headNode,int data)
{
	//先找节点,对节点的指针要进行移动
	Node* pPro = headNode;
	Node *pPos = headNode->next;
	while (pPos->data != data&&pPos->next!=NULL)
	{
		pPro = pPos;
		pPos = pPos->next;
	}
	if (pPos->next == NULL)
	{
		printf("你要删除的节点不存在!\n");
		return;
	}
	pPro->next = pPos->next;
	free(pPos);

}
//查找节点
void findNode(Node * headNode, int data)
{
	Node * pMove = headNode->next;
	while (pMove->data != data)
	{
		pMove = pMove->next;
	}
	printf("你想要找的节点数据:%d,已找到!\n", pMove->data);
}
//改动节点内的数据
void modifyNodeData(Node *headNode, int updata, int data)
{
	//这个和找节点的思路是一样的,先找到指定数据节点,再对其进行修改
	Node * pMove = headNode->next;
	while (pMove->data != data)
	{
		pMove = pMove->next;
	}
	pMove->data = updata;
	printf("修改数据成功!\n");

}
//输出节点的数据
void printList(Node * headList)
{
	Node * pMove = headList->next;
	while (pMove != headList)//当你访问节点的next里的地址不是头节点的地址继续向下走
	{
		printf("%d--", pMove->data);
		pMove = pMove->next;
	}
	printf("\n");
}
int main()
{
	Node *list = createList();

	for (int i = 1; i < 11; i++)
	{
		addNode(list, i);
	}
	
	printList(list);
	findNode(list, 5);
	printList(list);
	modifyNodeData(list, 45, 6);
	printList(list);
	deleteNode(list, 9);
	printList(list);
	return 0;
}



标签:Node,next,链表,headNode,单循环,pMove,data,节点
来源: https://blog.csdn.net/qq_52257334/article/details/120444245