C语言知识点(四):链表一(单链表)

本次主要介绍从尾部添加新节点

1、定义节点结构 

数据域:int x

指针域:struct Node *next

typedef struct Node
{
	int x;
	struct Node *next;
}node;

2、动态添加新节点

头结点:head 

尾节点:tail

插入节点:ins

通过将 tail->next = ins(将插入节点 插入链表尾部) ,设置 tail = ins (设置插入节点为尾节点),并且将 tail->next = NULL

        node *head = NULL;
	head = (node *)malloc(sizeof(node));
	head->x = 99;
	node *tail = head;
	for (int i = 0; i < 10; i++)
	{
		node *ins = (node *)malloc(sizeof(node));
		ins->x = i;
		tail->next = ins;
		tail = ins;
		tail->next = NULL;

	}

3、顺序遍历节点

    node *p=head;
	while (p!= NULL)
	{
		printf("%d\n", p->x);
		p = p->next;
	}

4、在pos位置插入新节点

void insertNode(int pos,int val,node *h)
{
	node *temp = (node *)malloc(sizeof(node));
	temp->x = val;
	int count = 0;
	while (h != NULL)
	{
		if (count == pos-1)
		{
			temp->next = h->next;
			h->next = temp;
			
		}
		count++;
		h = h->next;
	}
	temp = NULL;
}

5、在删除pos位置节点

//删除节点
void deleteNode(int pos, node *h)
{
	int count = 0;
	while (h != NULL)
	{
		if (count == pos-1)
		{
			if (h->next != NULL)
			{
				node* temp = h->next;   //定义临时temp指向要删除的节点
				h->next = temp->next;	//将要被删除的节点的前驱节点指向其后继节点
				free(temp);				//释放被删除节点的内存空间,防止内存泄漏
				temp = NULL;			//将temp指向NULL,防止产生野指针
				return;
			}
			else
			{
				printf("该节点不存在\n");
				return;
			}
		}
		count++;
		h = h->next;
	}
	printf("该节点不存在\n");
}

6、查询pos位置节点

node* findVal(int data,node *h)
{
	node *val = (node *)malloc(sizeof(node));
	val = h;
	int count = 1;
	while (val != NULL)
	{
		if (val->x == data)
			printf("找到数据为%d的节点,该节点是第%d个\n", data, count);
		count++;
		val = val->next;
	}
	return val;
}

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值