循环链表

按照书上的想法自己写了一个循环链表。每出现一个新的节点,就将这个节点的next链接到头指针。

虽然感觉有一些东西还是不太正确,但现在也找不出来,就先这样吧。

#include<iostream>
#include<cstdlib>
using namespace std;

typedef struct node{
	int data;
	struct node *next;
}	Node;

Node* Creatlinklist(int n)
{
	Node *head=(Node*)malloc(sizeof(Node));
	Node *p=head;
	for(int i=n;i>0;i--){
		p->next=(Node*)malloc(sizeof(Node));
		p=p->next;
		p->next=head;//形成循环
		cout<<i<<" ";
	}
	cout<<endl<<"Creat linklist has been down."<<endl;
	return head;
}

void Inputdata_linklist(Node *head,int n)
{
	Node *p=head->next;
	for(int i=0;i<n;i++){
		cin>>p->data;
		//cout<<p->data<<" ";
		p=p->next;
	}
	cout<<endl<<"Input has been down."<<endl;
}

void print(Node *head)
{
	Node *p=head->next;
	for(int i=0;i<3;i++){
		while(p!=head)
		{
			cout<<" "<<p->data;
			p=p->next;
		}
		cout<<endl;
		p=p->next;
	}
}

int main()
{
	int n;
	cin>>n;
	Node *head=Creatlinklist(n);
	Inputdata_linklist(head,n);
	print(head);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值