链表类 List.h

#pragma once
#include 
<iostream>
using namespace std;
#include 
<string>
typedef 
float T;
class List{
    
struct Node{
        T data;
        Node 
*next;
        Node(
const T& t=T()):data(t),next(NULL){}
    }
;
    Node
* head;
public:
    List():head(NULL)
{}//构造
    void clear(){//清空
        while(head!=NULL){
            Node
* p=head->next;
            delete head;
            head
=p;
        }
        
    }

    
~List(){clear();}//析构
    void insert_front(const T& t){//前面插入结点
        Node *p=new Node(t);
        p
->next=head;
        head
=p;
    }

    
void insert_back(const T& t){
        Node 
*p=new Node(t);
        
if(head==NULL)
            head
=p;
        
else{
            Node 
*q=head;
            
while(q->next!=NULL)
                q
=q->next;
            q
->next=p;  
        }

    }

    
void travel(){//遍历
        Node *p=head;
        
while(p!=NULL){
            cout
<<p->data;
            p
=p->next;
        }

        cout
<<endl;
    }

    
int size(){
        
int count=0;
        Node 
*p=head;
        
while(p!=NULL){
            count
++;
            p
=p->next;
        }

        
return count;
    }

    
bool empty(){return head==NULL;}
    T getHead()
{
        
if(head==NULL)
            
throw "No Head!";
        
return head->data;
    }

    T getTail()
{
        
if(head==NULL)
            
throw "No Tail!";
        Node 
*p=head;
        
while(p->next!=NULL)
            p
=p->next;
        
return p->data;
    }

    
int find(const T& t){
        
int pos=0;
        Node
* p=head;
        
while(p!=NULL){
            
if(p->data==t)
                
return pos;
            p
=p->next;
            pos
++;
        }

        
return -1;
    }

    Node
* getPointer(int pos){
        Node
* p=head;
        
for(int i=0;i<pos;i++)
            p
=p->next;
        
return p;    
    }

    
bool updata(const T& o,const T& n){
        
int pos=find(o);
        
if(pos==-1)
            
return false;
        Node
* p=getPointer(pos);
        p
->data=n;
        
return true;
    }

    
bool erase(const T& t){
        
int pos=find(t);
        
if(pos==-1)
            
return false;
        
if(pos==0){
            Node 
*p=head->next;
            delete head;
            head
=p;
        }

        
else{        
            Node
* pre=getPointer(pos-1);
            Node
* cur=pre->next;
            pre
->next=cur->next;
            delete cur;
        }

        
return true;
    }

    
void insert_back2(const T& t){
        Node
* p=new Node(t);
        
if(head==NULL)
            head
=p;
        
else{
            getPointer(size()
-1)->next=p;
        }

    }

}
;

posted on 2011-05-20 13:15 Hsssssss 阅读(145) 评论(0)  编辑 收藏 引用 所属分类: C++代码


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

常用链接

留言簿

文章分类

文章档案

收藏夹

搜索

最新评论