kai


私信TA

用户名:dotcpp0593017

访问量:560

签 名:

等  级
排  名 4894
经  验 1554
参赛次数 0
文章发表 18
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

/*

写一个函数del,用来删除动态链表中指定的节点

*/

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

typedef struct LNode{
	int num;
	struct LNode *next;
}LNode;

LNode* creat(int n)
{
	LNode *head,*p;
	head = (LNode *)malloc(sizeof(LNode));//建立头节点 
	p = head;
	head->num = 0;
	head->next = NULL;
	for(int i = 1;i<=n;i++)//使用尾插法对链表赋值 
	{
		LNode *newNode = (LNode *)malloc(sizeof(LNode));
		newNode->num = i;
		newNode->next = NULL;
		p->next = newNode;
		p = p->next;
	 } 
	 return head;
}

void del(int n,LNode *head)
{
	LNode *pre,*current;
	pre = head;//将头节点赋给pre 
	current = head->next;//将current的值变为头节点后面的那个值,即链表的第一个有效值 
	//从第一个有效的节点开始查询需要删除的节点;
	printf("delete node %d\n",n);
	while(current!=NULL)
	{
		//找到需要删除的节点,重新链接,释放待删除的节点
		if(current->num == n)
		{
			pre->next = current->next;//将current给间隔过去直接让pre的值指向current后面那个值 
			free(current);//释放current 
			break;//跳出循环 
		 } 
		 
		 pre = current;
		 current = current->next;
	 } 
}
int main()
{
	LNode *head, *p;
	int n;
	head = creat(10);
	printf("请输入需要删除的节点:1-10\n");
	scanf("%d", &n);
	del(n, head);
	int i = 1;
	p = head->next;
	while (p != NULL)
	{
		printf("p %d.num -> %d\n", i, p->num);
		p = p->next;
		i++;
	}
	return 0;

}


 

0.0分

2 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区

牛逼啊
2022-11-22 17:28:33
  • «
  • 1
  • »