C++数据结构 10 链表

#ifndef __LIST_H__
#define __LIST_H__

#include <iostream>
using namespace std;
template <class Type> class List;  //声明节点

template <class Type>
class ListNode    //节点
{
friend class List<Type>;
private:
    Type data;
    ListNode *link;
    ListNode(Type);
};

template <class Type>
class List{

public:
    List() {first=0;};  //初始化构造函数
    void Insert(Type);   //插入数据
    void Delet(Type);    //删除数据
    void convert();   //反转
    void Connect(List<Type>);  //连接两个
    void show();
private:
    ListNode<Type> *first;  //指向第一个
};

template <class Type>
ListNode<Type>::ListNode(Type element)//构造函数
{
  data=element;
  link=0;
}

template<class Type>
void List<Type>::Insert(Type K)
{
   ListNode<Type> *node= new ListNode<Type>(K);
   node->link=first;    //在头插入 ,把first指向第一个的节点赋给node link
   first=node;           //node指向就是第一个节点
}

template<class Type>
void List<Type>::show()  //显示
{
    for(ListNode<Type> *current=first;current;current=current->link)
    {
        cout<<current->data<<' ';
    }
    cout<<endl;
}

template<class Type>
void List<Type>::Delet(Type element) //删除数据
{
  ListNode<Type> *previous=0;  //保存前一个数据
  ListNode<Type> *current;  //保存现今的数据
  for(current=first;current&& current->data!=element;previous=current,current=current->link); //依次查找 数据
  if(current)
  {
      if(previous) previous->link=current->link;  //如果不是第一个数据 ,前一个节点指向到下一个节点
      else first=first->link;
      delete current;  //删除new的node
  }
}

template<class Type>
void List<Type>::convert()  //进行数据反转
{
   ListNode<Type> *p=first, *q=0;  //将第一个和最后一个交换
   while(p)
   {
       ListNode<Type> *r=q;q=p;
       p=p->link;
       q->link=r;
   }
   first=q;
}
template<class Type>
void List<Type>::Connect(List<Type> b)
{
    if(!first)   //如果第一个链表为空,将第二个链表的直接接在第一个的头部
    {first=b.first;
    return;
    }
    if(b.first)
    {
        ListNode<Type> *p;
        for(p=first;p->link;p=p->link);  //循环到最后一个数据
         p->link=b.first;         //将最后一个数的下一个接在第一个数的头部
    }
}



#endif // __LIST_H__

main

#include <iostream>
#include "List.h"
using namespace std;

int main()
{
    List<int> K;
    K.Insert(10);
    K.Insert(12);
    K.Insert(20);
    K.show();
    K.Delet(20);
    K.show();
    K.convert();
    K.show();
    //cout << "Hello world!" << endl;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值