指针、链表操作

蓝线表示删除ptCur项后

双向链表
蓝线表示删除ptCur项后

typedef struct NAME{
	char *name;
	struct NAME *pre;
	struct NAME *next;
}T_Name, *PT_Name;

static PT_Name g_ptNameHead;


void add_name(PT_Name ptNew)
{
	PT_Name ptCur;
	
	if (g_ptNameHead == NULL)
	{
		g_ptNameHead = ptNew;
	}
	else
	{
		ptCur = g_ptNameHead;
		while (ptCur->next)//最后一项为空,退出
		{
			ptCur = ptCur->next;
		}
		ptCur->next = ptNew;//指向新添加的项
		ptNew->pre  = ptCur;//新项指向前项
	}
}
void add_one_name()
{
	PT_Name ptNew;
	char *str;
	char name[128];
	
	printf("enter the name:");
	scanf("%s", name);

	str  = malloc(strlen(name) + 1);
	strcpy(str, name);
	/*初始化*/
	ptNew = malloc(sizeof(T_Name));
	ptNew->name = str;
	ptNew->pre  = NULL;
	ptNew->next = NULL;

	add_name(ptNew);
}
/*查找name*/
PT_Name get_name(char *name)
{
	PT_Name ptCur;
	if (g_ptNameHead == NULL)
	{
		return NULL;
	}
	else
	{
		ptCur = g_ptNameHead;
		do {  /*name相同则返回,否则继续查找*/
			if (strcmp(ptCur->name, name) == 0)
				return ptCur;
			else
				ptCur = ptCur->next;
		}while (ptCur);
	}
	return NULL;
}
/* 释放 */
void del_name(PT_Name ptDel)
{
	PT_Name ptCur;	
	PT_Name ptPre;	
	PT_Name ptNext;	
	/*删除的为第一项*/
	if (g_ptNameHead == ptDel)
	{
		g_ptNameHead = ptDel->next;
		return;
	}
	else
	{
		ptCur = g_ptNameHead->next;
		while (ptCur)
		{
			if (ptCur == ptDel)
			{
				/* 取出当前项的前一项和后一项 */
				ptPre  = ptCur->pre;
				ptNext = ptCur->next;
				ptPre->next = ptNext;//前一项next指向后一项
				if (ptNext)
				{
					ptNext->pre = ptPre;
				}
				break;
			}
			else
			{
				ptCur = ptCur->next;
			}
		}
	}
	/* 释放 */
	free(ptDel->name);
	free(ptDel);
}
void del_one_name()
{	/*先查找再删除*/
	PT_Name ptFind;
	char name[128];
	
	printf("enter the name:");
	scanf("%s", name);

	ptFind = get_name(name);
	if (ptFind == NULL)
	{
		printf("do not have this name\n");
		return ;
	}
	del_name(ptFind);
}

void list_all_name(void)
{
	PT_Name ptCur;
	int i = 0;
	ptCur = g_ptNameHead;
	while (ptCur)
	{	/*遍历 */
		printf("%02d : %s\n", i++, ptCur->name);
		ptCur = ptCur->next;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43542305/article/details/86064135
今日推荐