LeetCode237删除链表中的节点

程序:

#include<stdio.h>
#include<stdlib.h>
struct listdata{
	int num;
	struct listdata *next;
};

void deleteNode(struct listdata *node)
{
	struct listdata *tmp;
	tmp=node->next;
	node->num=tmp->num;
	node->next=tmp->next;
	free(tmp);
}

struct listdata *find(int n,struct listdata const *node)
{
	struct listdata *tmp;
	tmp=node;
	while(tmp)
	{
		if(tmp->num==n)
		{
			return tmp;
		}
		tmp=tmp->next;
	}
	return NULL;
	
}

void dayinlist(struct listdata *node)
{
	struct listdata *tmp;
	tmp=node;
	printf("链表:\n");
	while(tmp)
	{
		printf("%d\t",tmp->num);
		tmp=tmp->next;
	}
	printf("\n");
}

int main()
{
	printf("输入链表数据(-1结束):\n");
	struct listdata *head=NULL;
	struct listdata *new,*old;
	while(1)
	{
		new = (struct listdata *) malloc(sizeof(struct listdata));
		scanf("%d",&new->num);
		if(new->num==-1)
		{
			break;
		}
		else
		{
			if(head==NULL)
			{
				head=new;
			}
			else
			{
				old->next=new;
			}
		}
		new->next=NULL;
		old=new;
		
	}
	dayinlist(head);
	printf("输入要删除的数据:");
	int n;
	scanf("%d",&n);
	struct listdata *tmp;
	tmp=find(n,head);
	if(tmp==NULL)
	{
		printf("未找到");
	}
	else
	{
		deleteNode(tmp);
		dayinlist(head);
	}
	return 0;
}


比较顺利,没遇到什么大问题,链表前段时间熟悉过。
知识点
1.定义一个返回结构体指针的函数:
定义一个结构体:
struct 结构体名{};
定义结构体函数:
struct 结构体名 *(…)
{
//定义结构体数据
struct 结构体名 变量名{};

return 变量名;
}

2.向函数传结构体指针:
void 函数名(struct 结构体名 *(形参名))

3.定义一个结构体指针后,获取其中参数用->,例如node->num 。这种情况下用scanf赋值时,依然要加“&”

4.创建链表时必须有三个指针,head,new,old,之前一直纠结于是不是可以省取head这个头指针,这次发现,头指针是最重要的,头指针就是链表的代表,头指针就可以说是链表名,后面的new和old指针只是在构建链表的过程中用来过度的,链表创建完成就没什么用了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值