C++单链表实现(插入,查找,删除,销毁)

#include <iostream>
#include <cstdlib>
using namespace std;

struct Data{                    //数据部分 
	int key;
	//...
	bool operator==(const Data& d)const{ //重载运算符== 
		return key == d.key;    // && ... == ... 
	}
	bool operator!=(const Data& d)const{ //重载运算符!= 
		return key != d.key;    // || ... != ...
	}
};
struct Node{
	struct Data data;           //节点数据部分 
	struct Node* next;          //指向下一个节点的指针 
};

//新建一个节点,返回节点指针 
struct Node* Create_node(struct Data data){
	struct Node* p = (struct Node*)malloc(sizeof(struct Node));
	p->data = data;
	p->next = NULL;
	return p;
} 
//在链表尾部插入节点,返回头结点指针 
struct Node* Insert(struct Node* head, struct Node* add){
	if(head == NULL)            //当头结点为空时,add作为头结点,返回add 
		return add;
	struct Node* p = head;
	while(p->next != NULL)      //p指针链表尾节点 
		p = p->next;
	p->next = add;             //将节点add插入到链表尾部
	return head;               //返回头结点 
}
//删除节点,返回头结点
struct Node* Delete(struct Node* head, struct Data data){
	if(head == NULL)            //链表为空 
		return head;
	if(head->data == data){     //要删除的节点是头结点,释放头结点,返回第二个节点指针 
		struct Node *p = head->next;
		free(head);
		return p;
	}
	struct Node *p = head, *q = head->next;
	while(q != NULL && q->data != data){  //在链表中寻找data,p指向q的前一个节点 
		p = q;
		q = q->next;
	}
	if(q != NULL && q->data == data){     // 找到了要删除的节点 
		p->next = q->next;                // 删除节点 
		free(q);
	}
	return head;
} 
//搜索节点,返回节点指针 
struct Node* Search(struct Node* head, struct Data data){
	if(head == NULL || head->data == data)
		return head;
	struct Node* p = head->next;
	while(p != NULL){
		if(p->data == data)
			return p;
		p = p->next;
	}
	return NULL;                // 没找到 
}
//递归释放整个链表
void Destroy(struct Node* head){
	if(head != NULL){
		Destroy(head->next);
		free(head);
	}
} 
void print(struct Node* head){
	while(head != NULL){
		cout << head->data.key << endl;
		head = head->next;
	}
}
int main(int argc, char *argv[]){
	struct Data d1 = {2},d2 = {3}; //两个数据结构体 
	struct Node* head = NULL;      //头结点 
	struct Node* add = Create_node(d1);
	head = Insert(head,add);

	print(head);
	cout << endl;
	add = Create_node(d2);
	head = Insert(head,add);
	print(head);
	cout << endl;
	struct Node* s = Search(head,d1);
	if(s != NULL){
		cout << "find it ";
		cout << s->data.key << endl;
	}
	head = Delete(head,d2);
	print(head);
	Destroy(head);
	head = NULL;                     //养成良好习惯 
	return 0;
}

 

  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值