zoukankan      html  css  js  c++  java
  • C++实现简易单向链表

    #include <iostream>
    #include <stdlib.h>
    #include <stdbool.h>
    
    
    using namespace std;
    //结点
    class Node
    {
    public:
    	int data;
    	Node* next;
    	Node(int d)
    	{
    		data = d;
    		next = NULL;
    	}
    };
    //链表
    class List
    {
    	Node* head;
    public:
    	List()
    	{
    		head =NULL;
    	}
    	void init(Node *p)
    	{
    		head = p;
    	}
    	//插入
    	void insert(Node* p)
    	{
    		p -> next = head;
    		head = p;
    	}
    	//删除
    	Node* delete_node(Node* p)
    	{
    		Node** pnext;
    		for(pnext = &head;*pnext;pnext = &(*pnext) ->next)
    		{
    			if(*pnext == p)
    			{
    				*pnext = p -> next;
    				return p;
    			}
    		}
    		return NULL;
    	}
    	//遍历链表
    	/*void trave_list(Node* p)
    	{
    		for(p = head;p;p = p ->next)
    		{
    			cout<< p->data << endl;
    		}
    	}*/
    	//查找
    	Node* search_list(int key)
    	{
    		Node* p;
    		p =head;
    		while(p)
    		{
    			if(p->data == key)
    			{
    				cout << "----" << p->data << "----" << endl;
    				return p;
    			}
    			p = p->next;
    		}
    		return NULL;
    	}
    	//销毁链表
    	void destroy()
    	{
    		Node* p;
    		Node* q;
    		for(p = head;p;)
    		{
    			q = p -> next;
    			delete p;
    			p = q;
    		}
    		head = NULL;
    	}
    	friend ostream& operator << (ostream& os,List& list);
    };
    //遍历并打印
    ostream& operator << (ostream& os,List& list)
    {
    	Node *p;
    	for(p = list.head;p;p = p ->next)
    	{
    		cout<< p->data << " ";
    	}
    	return os;
    
    
    }
    int main()
    {
    	List list;
    	Node *p;
    	for(int i =0;i<10;i++)
    	{
    		p = new Node(i);
    		list.insert(p);
    
    
    	}
    	p = list.search_list(5);//在链表中找到结点
    	Node* t = list.delete_node(p);//把结点移除
    	list.delete_node(t);//释放结点空间
    	//list.trave_list(p);
    	cout<< list << endl;//遍历并打印
    	list.destroy();//销毁
    	return 0;
    	
    }
    
    
  • 相关阅读:
    JS的IE和FF兼容性问题汇总
    解决flash挡住层的问题
    javascript 代码优化工具 UglifyJS
    理解面向对象
    js中的等号与非等号
    js 的数据类型转换
    js优化 ----js的有序加载
    各浏览器对页面外部资源加载的策略
    js 执行效率
    脚本的加载,解析,与执行
  • 原文地址:https://www.cnblogs.com/gzk1171848896/p/9449989.html
Copyright © 2011-2022 走看看