您的位置:首页 > 编程语言 > C语言/C++

C++实现链表函数

2014-09-15 10:24 176 查看
//链表,头结点中要放置元素

#include<iostream>

using namespace std;

struct listnode

{
int data;
listnode* next;

};

listnode* createlistnode(int value)

{
listnode* pnode=new listnode;
pnode->data=value;
pnode->next=NULL;
return pnode;

}

void connectlistnode(listnode* pcurrent,listnode* pnext)

{
if(pcurrent==NULL)
{
cout<<"error"<<endl;
return;
}
pcurrent->next=pnext;

}

void printlistnode(listnode* pnode)

{
if(pnode==NULL)
cout<<"the listnode is null"<<endl;
else
cout<<pnode->data<<" ";

}

void printlist(listnode* phead)

{
listnode* pnode=phead;
if(phead==NULL)
cout<<"the list is null"<<endl;
else
{
while(pnode!=NULL)
{
cout<<pnode->data<<" ";
pnode=pnode->next;
}
cout<<endl;
}

}

void destroylist(listnode* phead)

{
listnode* pnode=phead;
while(phead!=NULL)
{
phead=phead->next;
delete pnode;
pnode=phead;
}
pnode=NULL;
phead=NULL;

}

void addtotail(listnode** phead,int value)//注意这里必须把phead设置为指向指针的指针,因为当链表为空时,插入一个节点,此时肯定会改变头指针

{
listnode* pnodenew=new listnode;
pnodenew->data=value;
pnodenew->next=NULL;
if(*phead==NULL)
*phead=pnodenew;
else
{
listnode* pnode=*phead;
while(pnode->next!=NULL)
pnode=pnode->next;
pnode->next=pnodenew;
}

}

void removenode(listnode** phead,int value)

{
if(phead==NULL||*phead==NULL)
return ;
listnode* ptobedeleted=NULL;
if((*phead)->data==value)
{
ptobedeleted=*phead;
*phead=(*phead)->next;
}
else
{
listnode* pnode=*phead;
while(pnode->next!=NULL&&pnode->next->data!=value)
pnode=pnode->next;
if(pnode->next!=NULL&&pnode->next->data==value)
{
ptobedeleted=pnode->next;
pnode->next=pnode->next->next;
}
}
if(ptobedeleted!=NULL)
{
delete ptobedeleted;
ptobedeleted=NULL;
}

}

int main()

{
//链表的第一种构造方式
listnode* pnode1 = createlistnode(1);
listnode** head=&pnode1;
addtotail(head,2);
addtotail(head,3);
addtotail(head,4);
addtotail(head,5);
addtotail(head,6);
addtotail(head,7);
addtotail(head,8);
addtotail(head,9);
printlist(pnode1);

//链表的第二种构造方式
listnode* pnode11 = createlistnode(1);
listnode* pnode2 = createlistnode(2);
listnode* pnode3 = createlistnode(3);
listnode* pnode4 = createlistnode(4);
listnode* pnode5 = createlistnode(5);
listnode* pnode6 = createlistnode(6);

connectlistnode(pnode11, pnode2);
connectlistnode(pnode2, pnode3);
connectlistnode(pnode3, pnode4);
connectlistnode(pnode4, pnode5);
connectlistnode(pnode5, pnode6);
printlist(pnode11);

//链表的第三种构造方式
listnode* pnode13=NULL;
listnode** head3=&pnode13;
addtotail(head3,2);
addtotail(head3,3);
addtotail(head3,4);
addtotail(head3,5);
addtotail(head3,6);
addtotail(head3,7);
addtotail(head3,8);
addtotail(head3,9);
printlist(*head3);
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: