C++数据结构 单链表(模板类)

利用模板类实现单链表及其功能

需要实现的操作:

[1] push_back       [2] push_front

[3] show_list       [0] quit_system

[4] pop_back        [5] pop_front

[6] insert_val      [7] delete_val

[8] find            [9]length

[10] clear          [11]destroy

[12] reserv         [13]sort

头文件源代码:

#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED

#include <iostream>
using namespace std;

template<class Type>
class List;

template<class Type>
class ListNode
{
	friend class List<Type>;
public:
	ListNode():data(Type()),next(NULL)
	{}
	ListNode(Type d, ListNode<Type> *n=NULL)
		:data(d),next(n)
	{}
	~ListNode()
	{}
public:
	void SetData(Type d)
	{data = d;}
	Type GetData()const
	{return data;}
private:
	Type data;
	ListNode<Type> *next;
};

template<class Type>
class List
{
public:
	List()
	{
		first = last = Buynode();
	}
	~List()
	{
	    List<Type>::destroy();
	}
public:
	void push_back(const Type &x);
	void push_front(const Type &x);
	void show_list()const;
	void pop_back();
	void pop_front();
	void insert_val(const Type &x);
	void delete_val(const Type &x);
	bool find(const Type &x);
	Type length();
	void clear();
	void destroy();                        //摧毁该顺序表
	void reserv();                         //反转
	void sort();
protected:
	ListNode<Type>* Buynode(Type x = Type())
	{
		ListNode<Type> *p = new ListNode<Type>(x);
		return p;
	}
private:
	ListNode<Type> *first;
	ListNode<Type> *last;
};

template<class Type>
void List<Type>::push_back(const Type &x)
{
    ListNode<Type> *s = Buynode(x);
    last->next = s;
    last = s;
    first->data++;
}

template<class Type>
void List<Type>::push_front(const Type &x)
{
    ListNode<Type> *s = Buynode(x);
    s->next=first->next ;
    first->next=s;
    if(first == last)
        last = s;
    first->data++;
}

template<class Type>
void List<Type>::show_list()const
{
    ListNode<Type> *p = first->next;
    while(p != NULL)
    {
        cout<<p->data<<" ";
        p = p->next;
    }
    cout<<endl;
}

template<class Type>
void List<Type>::pop_back()
{
    if(first->data == 0)
        return;
    ListNode<Type> *p = first;
    while(p->next != last)
        p = p->next;
    ListNode<Type> *q = p->next;
    p->next = NULL;
    last = p;
    delete q;
    first->data--;
}

template<class Type>
void List<Type>::pop_front()
{
    ListNode<Type> *p = first->next;
    first->next = p->next;
    p = NULL;
    delete p;
    if(first->data == 1)
        last = first;
    first->data--;
}

template<class Type>
void List<Type>::insert_val(const Type &x)
{
    ListNode<Type> *s =  Buynode(x);
    ListNode<Type> *p =  first->next;
    if(p->data > s->data)
    {
        push_front(s->data);
    }
    else if(first->data < s->data)
    {
        push_back(s->data);
    }
    else
        {
            while((p->data < x )&& (p->next->data<x))
            {
                p = p->next;
            }
            s->next=p->next ;
            p->next = s;
            first->data++;
        }
}

template<class Type>
void List<Type>::delete_val(const Type &x)
{
    ListNode<Type> *p = first->next;
    ListNode<Type> *s =  Buynode(x);
    if(x == p->data)
    {
        pop_front();
    }
    else
    {
         while((p->data != x) && (p->next->data != x))
        {
            p = p->next;
        }
        p->next = p->next->next;
        ListNode<Type> *q = p->next;
        delete q;
        first->data--;
    }
}

template<class Type>
bool List<Type>::find(const Type &x)
{
    ListNode<Type> *p = first->next;
    while(p!=NULL && p->data!=x)
        p = p->next;
        return p;
    }

template<class Type>
Type List<Type>::length()
{
    cout<<"length = "<<first->data<<endl;
    return first->data;
}

template<class Type>
void List<Type>::clear()
{
  while(first->data >0)
    pop_front();
}

template<class Type>
void List<Type>::destroy()//摧毁该顺序表
{
    clear();
    delete first;
    first = last = NULL;
}

template<class Type>
void List<Type>::reserv() //反转,将整个表空间逆置
{
    ListNode<Type> *p = first->next;
    ListNode<Type> *curr = p->next;
    ListNode<Type> *tmp = NULL;

    first->next->next = NULL;
    while (curr)   //将将直接后继指向当前指针的next
    {
        tmp = curr->next;
        curr->next = p;
        p = curr;
        curr = tmp;
    }
    first->next = p;
}

template<class Type>
void List<Type>::sort()
{
    ListNode<Type> *s = first->next;
    while (s->next)
    {
        ListNode<Type> *p = s;
        while(p->next)
        {
             if(s->data > p->next->data)
                {
                    Type tmp = s->data;
                    s->data = p->next->data;
                    p->next->data = tmp;
                }
                p = p->next;
        }
        s = s->next;
    }
}

#endif // LIST_H_INCLUDED

主函数:

<pre name="code" class="cpp">#include"List.h"

int main()
{
    List<int> mylist;
	int select = 1;
	int Item;
	int pos;
	while(select)
	{
		cout<<"**************************************"<<endl;
		cout<<"* [1] push_back       [2] push_front *"<<endl;
		cout<<"* [3] show_list       [0] quit_system*"<<endl;
		cout<<"* [4] pop_back        [5] pop_front  *"<<endl;
		cout<<"* [6] insert_val      [7] delete_val *"<<endl;
		cout<<"* [8] find            [9]length      *"<<endl;
		cout<<"* [10] clear          [11]destroy    *"<<endl;
		cout<<"* [12] reserv         [13]sort       *"<<endl;
		cout<<"**************************************"<<endl;
		cout<<"请选择:>";
		cin>>select;
		switch(select)
        {
        case 1:
			cout<<"请输入要插入的值(-1结束):>";
			while(cin>>Item, Item!=-1)
			{
				mylist.push_back(Item);
			}
			break;
		case 2:
			cout<<"请输入要插入的值(-1结束):>";
			while(cin>>Item, Item!=-1)
			{
				mylist.push_front(Item);
			}
			break;
		case 3:
			mylist.show_list();
			break;
        case 4:
            mylist.pop_back();
            break;
        case 5:
            mylist.pop_front();
            break;
        case 6:
            cout<<"请输入要插入的值:>";
            cin>>Item;
            mylist.insert_val(Item);
            break;
		case 7:
			cout<<"请输入要删除的值:>";
			cin>>Item;
			mylist.delete_val(Item);
			break;
		case 8:
			cout<<"请输入要查找的值:>";
			cin>>Item;
			mylist.find(Item);
			break;
        case 9:
            mylist.length();
            break;
        case 10:
            mylist.clear();
            break;
        case 11:
            mylist.destroy();
            break;
        case 12:
            mylist.reserv();
            break;
        case 13:
            mylist.sort();
            break;
		default:
			break;
        }
    }
}
				
时间: 2024-10-15 09:10:42

C++数据结构 单链表(模板类)的相关文章

C++ 单链表模板类实现

单链表的C语言描述 基本运算的算法--置空表.求表的长度.取结点.定位运算.插入运算.删除运算.建立不带头结点的单链表(头插入法建表).建立带头结点的单链表(尾插入法建表),输出带头结点的单链表 #include<cstdio>#include<iostream>using namespace std;template <class T>class Linklist{private: struct node { T date; node * next; node():n

数据结构—单链表(类C语言描写叙述)

单链表 1.链接存储方法 链接方式存储的线性表简称为链表(Linked List). 链表的详细存储表示为: ① 用一组随意的存储单元来存放线性表的结点(这组存储单元既能够是连续的.也能够是不连续的) ② 链表中结点的逻辑次序和物理次序不一定同样.为了能正确表示结点间的逻辑关系,在存储每一个结点值的同一时候,还必须存储指示其后继结点的地址(或位置)信息(称为指针(pointer)或链(link)) 注意: 链式存储是最经常使用的存储方式之中的一个.它不仅可用来表示线性表.并且可用来表示各种非线性

单链表(模板类)

#include<iostream>#include<assert.h>using namespace std; template <class T>struct Node{ Node(const T& x) :_data(x) , _pNext(NULL) { } Node<T> *_pNext; T _data;};template <class T>class SList{public: SList() :_pHead(NULL)

C++ 数据结构 双链表(模板类)

#ifndef DLIST_H_INCLUDED #define DLIST_H_INCLUDED #include<iostream> using namespace std; template<class Type> class DList; template<class Type> class ListNode { friend class DList<Type>; public: ListNode():data(Type()),next(NULL),

分享一个线程安全的单例模板类

单例模式应该说是最简单的设计模式了.在此分享一个线程安全的单例模板类. template <typename Type> class CSingleton { public: static Type* GetInstance() { // kBeingCreatedMarker用来表示单例实例正在创建过程中. // 此处初始化为1是因为操作系统不会分配地址为1的指针. static const volatile intptr_t kBeingCreatedMarker = 1; // 如果m_

python实现数据结构单链表

#python实现数据结构单链表 # -*- coding: utf-8 -*- class Node(object): """节点""" def __init__(self, elem): self.elem = elem self.next = None # 节点一开始初始化的时候并不知道下一个元素的地址,所以先设置为空 class SingLinkList(object): """单链表""

[数据结构]线性表之单链表的类模板实现

类的具体实现如下: ///////////////////////// #include"LinearList.h" #include <iostream> #include <cstdlib> using namespace std; template<class T> struct LinkNode //链表节点类 { T data; LinkNode<T>* link; LinkNode(LinkNode<T>* ptr

数据结构-单链表-类定义2-C++

上一次的C++链表实现两个单链表的连接不太理想,此次听了一些视频课,自己补了个尾插法,很好的实现了两个链表的连接,当然了,我也是刚接触,可能是C++的一些语法还不太清楚,不过硬是花了一些时间尽量在数据结构中将c++的语言特点表现出来.一开始也是不愿意读c++的数据结构,只是一种挑战心里,不想读着读着感觉自己太low了,c++的内容更加丰富,所以还得多多练习...... 头文件 1 #ifndef LIST_H 2 #define LIST_H 3 #include <iostream> 4 5

算法与数据结构基础3:简单单链表List类的实现

简单的单链表实现,数据类型定义成了int,如果要通用,需要改成模板类,然后稍微修改下就可以了. // List.h #include <cstdio> #include <cassert> #include <iostream> using namespace std; class List { public: // ************************************************************************** //