链表的节点结构:
struct Node {
int element;//数据类型
Node *next;//指向下一个节点
};
链表的创建 :
Node *head=NULL;//头结点
Node *tail=NULL;//尾节点
链表的插入
Node *p=new Node; //新建节点
std::cout<<"input number:";
std::cin>>p->element;
if(head==NULL){
head=tail=p; //如果链表为空,将p节点作为头尾节点
p->next=NULL;
}
else{
tail->next=p; //将p节点插到链表最后
p->next=NULL;
tail=p; //将p节点作为尾节点
}
链表的遍历
Node *p=head;
while(p!=NULL){
std::cout<<p->element<<" " ;
p=p->next;
}
总结上述:
#include <iostream>
struct Node
{
int element;
Node*next;
};
int main()
{
Node *head=NULL;
Node *tail=NULL;
Node *p=new Node ;
std::cout<<"please input integers to build the link(0 to end) :";
std::cin>>p->element;
while(p->element!=0){
if(head==NULL){
head=tail=p;
p->next=NULL;
}
else {
tail->next=p;
p->next=NULL;
tail=p;
}
p=new Node;
std::cout<<"input number :";
std::cin>>p->element;
}
p=head;
std::cout<<"Link elements: ";
while(p!=NULL){
std::cout<<p->element<<" ";
p=p->next;
}
std::cout<<std::endl;
return 0;
}