单链表的建立与删除 (使用头插法和尾插法实现)

链表以及函数的声明,声明在node.h文件中

#ifndef _NODE_H


struct node
{
	int data;
	struct node *next;
};

int isEmpty(node* L);
node* Find(int x, node* L);
int isLast(node *p, node *L);
node* findPre(int x, node* L);
void del(int x, node* L);
void insert1(int x, node *P);
void insert2(int x, node* P);
void delist(node *L);
void print(node* L);



#endif

具体实现,在cpp文件中

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

int isEmpty(node* L)//链表是否为空
{
	return L->next == NULL;
}
node* Find(int x, node* L)//寻找某一个元素
{
	node *p;
	p = L->next;
	while (p != NULL&&p->data != x)
		p = p->next;
	return p;
}
int isLast(node *p, node *L)//是否是最后一个元素
{
	return p->next == NULL;
}
node* findPre(int x, node* L)//寻找某一个节点的前一个节点
{
	node *p;
	p = L;
	while (p->next != NULL&&p->next->data != x)
		p = p->next;
	return p;
}
void del(int x, node* L)//删除某一个节点
{
	node *p, *q;
	p = findPre(x, L);
	if (!isLast(p, L))
	{
		q = p->next;
		p->next = q->next;
		free(q);
	}
}
void insert1(int x, node *P)//插入节点,使用头插法
{
	node* tmp;
	tmp = (node*)malloc(sizeof(struct node));
	tmp->data = x;
	tmp->next = P->next;
	P->next = tmp;
}
void insert2(int x, node* P)//插入节点,使用尾插法
{
	node *last,*tmp;
	last = P;
	tmp = (node*)malloc(sizeof(struct node));
	tmp->data = x;
	while (last->next != NULL)
		last = last->next;
	tmp->next = NULL;
	last->next = tmp;
	last = tmp;
}
void delist(node *L)//删除整个链表
{
	node *p, *tmp;
	p = L->next;
	L->next = NULL;
	while (p != NULL)
	{
		tmp = p->next;
		free(p);
		p = tmp;
	}
}
void print(node* L)
{
	node *p;
	p = L->next;
	while (p != NULL)
	{
		printf_s("%d ", p->data);
		p = p->next;
	}
}

int main()
{
	struct node *head;
	head = (struct node *)malloc(sizeof(struct node));
	head->next = NULL;
	int n, i, tmp;
	while (scanf_s("%d", &n) != EOF)
	{
		for (i = 0; i < n; i++)
		{
			scanf_s("%d", &tmp);
			insert2(tmp, head);
		}
		print(head);
		printf_s("\n请输入要删除的元素:");
		scanf_s("%d", &tmp);
		del(tmp, head);
		print(head);
	}
	getchar();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值