C 中的链表实现
创建列表节点
class listNode
{
public:
int data;
listNode *next;
listNode(int val):data(val),next(NULL){}
};
创建 List 类
class List
{
public:
listNode *head;
List():head(NULL){}
void insertAtBegin(int val);
void insertAtEnd(int val);
void insertAtPos(int val);
void remove(int val);
void print();
~List();
};
在列表的开头插入一个新节点
void List::insertAtBegin(int val)//inserting at front of list
{
listNode *newnode = new listNode(val);
newnode->next=this->head;
this->head=newnode;
}
在列表末尾插入一个新节点
void List::insertAtEnd(int val) //inserting at end of list
{
if(head==NULL)
{
insertAtBegin(val);
return;
}
listNode *newnode = new listNode(val);
listNode *ptr=this->head;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=newnode;
}
插入列表中的特定位置
void List::insertAtPos(int pos,int val)
{
listNode *newnode=new listNode(val);
if(pos==1)
{
//as head
newnode->next=this->head;
this->head=newnode;
return;
}
pos--;
listNode *ptr=this->head;
while(ptr!=NULL && --pos)
{
ptr=ptr->next;
}
if(ptr==NULL)
return;//not enough elements
newnode->next=ptr->next;
ptr->next=newnode;
}
从列表中删除节点
void List::remove(int toBeRemoved)//removing an element
{
if(this->head==NULL)
return; //empty
if(this->head->data==toBeRemoved)
{
//first node to be removed
listNode *temp=this->head;
this->head=this->head->next;
delete(temp);
return;
}
listNode *ptr=this->head;
while(ptr->next!=NULL && ptr->next->data!=toBeRemoved)
ptr=ptr->next;
if(ptr->next==NULL)
return;//not found
listNode *temp=ptr->next;
ptr->next=ptr->next->next;
delete(temp);
}
打印列表
void List::print()//printing the list
{
listNode *ptr=this->head;
while(ptr!=NULL)
{
cout<<ptr->data<<" " ;
ptr=ptr->next;
}
cout<<endl;
}
列表的析构函数
List::~List()
{
listNode *ptr=this->head,*next=NULL;
while(ptr!=NULL)
{
next=ptr->next;
delete(ptr);
ptr=next;
}
}