c++链表的操作

#include <iostream>
using namespace std;
class Item
{
      public:
          friend class List;
      private:
          Item(int d=0){data=d;next=0;}
          Item *next;
          int data;
};
class List
{
    private:
      Item *list;
      Item *endl();
    public:
        List(){list =NULL;}
        List(int d){list=new Item(d);}
        int print();//输出
        int insert(int d=0);///前插入节点
        int append(int d=0);//尾插入节点
        void cat(List &il);//连接
        void reverse();//删除节点
        int length();//求链表长度
        
};
int List::length()
{
    int len=0;
    Item *tp;
    tp=list;
    while(tp!=NULL)
    {
     len++;
     tp=tp->next;
    }
    return len;
}
void List::reverse()
{
    if(list==NULL)
     cout<<"is empty...";
    Item *tp;
    tp=list->next;
    delete[] list;
    list=tp;
}
int List::append(int d)
{
    Item *tp=new Item(d);
    Item *p;
    
    if(list==NULL)
    list=tp;
  else
  {
    p=list;
    while(true)
    {
      if(p->next==NULL)
      {
        p->next=tp;
        break;
      }
      p=p->next;
    }
  }
  return 0;
}
int List::insert(int d)
{
      Item *p=new Item(d);
    p->next=list;
    list=p;
    return 1;
}
void List::cat(List &il)
{
  Item *p=il.list;
  while(p)
  {
    append(p->data);
    p=p->next;
  }
}
int List::print()
{
    if(list==0)
    {

     cout<<"empty\n";
     return 0;
    }
    cout<<"(";
    int cnt=0;
    Item *pt=list;
    while(pt)
    {
     cnt++;
     cout<<pt->data<<" ";
     pt=pt->next;
    }
    cout<<")\n";
    return cnt;  
}
int main()
{
    List li(9);
    li.append(8);
    li.insert(8);
    li.insert(4);
    li.insert(3);
      List L(0);
    L.insert(2);
    L.append(4);
    L.append(3);
    L.append(6);
    L.cat(li);
    L.reverse();
    L.reverse();
    L.print();
    cout<<"\n该链表的长度为:"<<L.length()<<"\n";
    getchar();
      return 0;  
}






你可能感兴趣的:(C++,职场,单链表,休闲)