29
2012
09

linux下练习 c++ 链表操作

code:

#include <iostream>
using namespace std;
typedef int T;
class List
{
struct Node
{
T data;
Node * next;
Node(const T&d=T()):data(d),next(0){}
};
Node * head;
public:
List():head(NULL)
{
cout<<"…list初始化完成…\n";
}
void push_front(const T&d)//前插法
{
Node * p=new Node(d);
p->next=head;
head=p;
}
void push_behand(const T&d)//尾插法
{
Node *ph=head;
while(ph->next!=NULL) ph=ph->next;
Node * p=new Node(d);
ph->next=p;
}
void insert(const T&d,int pos)//任意位置插入
{
Node * p=new Node(d);
Node *& pn=getptr(pos);
p->next=pn;
pn=p;
/*
if(pos<=0)
{
    p->next=head;
    head=p;
}
else
{
Node * ph=head;
while(pos-->1 && ph->next !=NULL)
{
ph=ph->next;
}
p->next=ph->next;
ph->next=p;
}
*/
}
void remove(int pos)
{
if(pos<0) return ;
Node *& pn=getptr(pos);
Node *p=pn;
pn=pn->next;
delete p;
}
Node *& getptr(int pos)
{
if(pos<=0) return head;
Node * p =head;
while(pos-->1 && p->next !=NULL)
p=p->next;
return (*p).next; 
}
void travel()const//遍历
{
Node * p=head;
while(p!=NULL)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<endl;
}
void clear()//清空内存
{
while(head != NULL)
{
Node *p=head->next;
delete head;
head=p;
}
}
~List()
{
clear();
cout<<"…内存释放完成…\n";
}
};
int main()
{
List l;
l.push_front(5);
l.push_front(4);
l.push_front(7);
l.push_front(6);
l.push_behand(45);
l.push_behand(48);
l.insert(100,0);//小于0位置就插入到最前
l.insert(99,6);//插入到指定位置
l.insert(991,100);//大于最后位置就插入到最后
l.remove(1);
l.remove(0);
l.travel();
return 0;
}

 


list.cpp


 


g++ -o list.out list.cpp


./list.out



版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。