PTA链表编程题常用函数(自用)更新中

#include<stdio.h>
#include<malloc.h>

#define vt int

struct node
{
	vt x;
	struct node *nxt;
};

struct node * mkempty()
{//创建空指针
	struct node *p = (struct node *)malloc(sizeof(struct node));
	p->x = NULL;
	p->nxt = NULL;
	return p;
}

struct node * mknode(vt x)
{//创建指针
	struct node *p = (struct node *)malloc(sizeof(struct node));
	p->x = x;
	p->nxt = NULL;
	return p;
}

struct node * read(int n)
{//读取链表
    struct node *head = NULL, *str = NULL;
	int x;
    for(int i = 1; i <= n; i ++ )
	{
        scanf("%d", &x);
		struct node *p = (struct node *)malloc(sizeof(struct node));
		p->x = x;
		p->nxt = NULL;
		if (NULL == head)
			head = p;
		else
			str->nxt = p;
		str = p;
	}
	return head;
}

struct node * read()
{//读取链表
	struct node *head = NULL, *str = NULL;
	int x;
	while(~scanf("%d", &x))
	{
        if(x == -1) break;
		struct node *p = (struct node *)malloc(sizeof(struct node));
		p->x = x;
		p->nxt = NULL;
		if (NULL == head)
			head = p;
		else
			str->nxt = p;
		str = p;
	}
	return head;
}

struct node *find(struct node *L,vt x)
{//查找链表中第一个出现元素x的地址
	while(L)
	{
		if(L->x == x) return L;
		L = L->nxt;
	}
	return NULL;
} 

void cout(struct node *L,vt x)
{//输出链表,如果x为0则表示带头指针
	if(!x) L = L->nxt;
	if (L == NULL)
		printf("NULL\n");
	while (L)
	{
		if (L->nxt == NULL)
			printf("%d\n", L->x);
		else
			printf("%d ", L->x);
		L = L->nxt;
	}
}

void insert(struct node *L, vt x)
{//后插元素
	struct node *p = (struct node *)malloc(sizeof(struct node));
	p->x = x;
	p->nxt = NULL;
	if (NULL == L)
		L = p;
	else
	{
		p->nxt = L->nxt;
		L->nxt = p;
	}
}

void push(struct node *L,vt x)
{//在链表尾部加入新的元素
	while(L && L->nxt != NULL) L = L->nxt;
	insert(L,x);
}

struct node *later(struct node *L,int x)
{//返回该指针后第x个的指针地址
	while(x && L)
	{
		x --;
		L = L->nxt;
	}
	if(x || !L)
	{
		return NULL;
	}
	return L;
}

int Len(struct node *L)
{//求链表元素个数
	int cnt = 0;
	while(L)
	{
		L = L->nxt;
		cnt ++;
	}
	return cnt;
}

void dele(struct node *L)
{//删除后元素
	if(L && L->nxt != NULL)
	{
		auto it = L->nxt;
		L->nxt = it->nxt;
		free(it);
	}
}

void clear(struct node *L)
{//清空内存
	while(L)
	{
		auto it = L->nxt;
		free(L);
		L = it;
	}
}

int main()
{

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值