#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;
}
PTA链表编程题常用函数(自用)更新中
于 2024-04-01 21:48:40 首次发布