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

#include 
#include 
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;
}

 

你可能感兴趣的:(C/C++,数据结构与算法)