zoukankan      html  css  js  c++  java
  • 单向链表

     单向链表C++

    class IntSLLNode
    {
    public:
    	IntSLLNode()
    	{
    		next = 0;
    	}
    	IntSLLNode(int i, IntSLLNode *in = 0)
    	{
    		info = i;
    		next = in;
    	}
    	int info;
    	IntSLLNode *next;
    private:
    };
    
    class IntSLList
    {
    public:
    	IntSLList()
    	{
    		head = tail = 0;
    	}
    
    	~IntSLList();
    	int isEmpty()
    	{
    		return head == 0;
    	}
    
    	void addToHead(int);
    	void addToTail(int);
    	int deleteFromHead();
    	int deleteFromTail();
    	void deleteNode(int);
    	bool isInList(int)const;
    
    private:
    	IntSLLNode *head, *tail;
    };
    
    IntSLList::~IntSLList()
    {
    	for (IntSLLNode *p; isEmpty();)
    	{
    		p = head->next;
    		delete head;
    		head = p;
    	}
    }
    
    void IntSLList::addToHead(int el)
    {
    	head = new IntSLLNode(el, head);
    	if (tail == 0)
    		tail = head;
    }
    
    void IntSLList::addToTail(int el)
    {
    	if (tail != 0)
    	{
    		tail->next = new IntSLLNode(el);
    		tail = tail->next;
    	}
    	else
    		head = tail = new IntSLLNode(el);
    }
    
    int IntSLList::deleteFromHead()
    {
    	int el = head->info;
    	IntSLLNode *temp = head;
    	if (head == tail)
    	{
    		head = tail = 0;
    	}
    	else
    	{
    		head = head->next;
    	}
    	delete temp;
    	return el;
    }
    
    int IntSLList::deleteFromTail()
    {
    	int el = tail->info;
    	if (head == tail) 
    	{
    		delete head;
    		head = tail = 0;
    	}
    	else
    	{
    		IntSLLNode *temp;
    		for (temp = head; temp->next != tail; temp = temp->next)
    			delete temp;
    		tail = temp;
    		tail->next = 0;
    	}
    	return el;
    }
    void  IntSLList::deleteNode(int el)
    {
    	if (head != 0)
    		if (head == tail && el == head->info)
    		{
    			delete head;
    			head = tail = 0;
    		}
    		else if (el==head->info)
    		{
    			IntSLLNode *temp = head;
    			head = head->next;
    			delete temp;
    		}
    		else
    		{
    			IntSLLNode *temp, *pred;
    			for (pred = head, temp = head->next; temp != 0 && !(temp->info == el); pred = pred->next, temp = temp->next);
    			if (temp != 0)
    			{
    				pred->next = temp->next;
    				if (temp->next)
    					tail = pred;
    				delete temp;
    			}
    		}
    }
    
    bool IntSLList::isInList(int el)const
    {
    	IntSLLNode *temp;
    	for (temp = head; temp != 0 && !(temp->info = el); temp = temp->next)
    		return temp != 0;
    }
    天上我才必有用,千金散尽还复来!
  • 相关阅读:
    HDU 5501
    CF #324 DIV2 E题
    CF #324 DIV2 C题
    利用位操作实现加减运算(不用+ -号)
    【Leetcode】120. 三角形最小路径和
    删除排序链表中的重复元素
    【python】二分查找
    如何在不添加新数组的情况下移除元素?
    三/四 数之和,双指针法,细节很多
    【转】字符串相关操作
  • 原文地址:https://www.cnblogs.com/lutaishi/p/13436318.html
Copyright © 2011-2022 走看看