链表的创建

链表的节点结构:

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值