数据结构实验之链表

建立链表主要有两种方法 头插法和尾插法
头插法主要用于建立逆向链表,尾插法主要用于建立顺序链表
顺序链表如下 尾插法

#include<cstdio>
using namespace std;
struct node
{
	int data;
	node *next;//结构体指针
};
int main()
{
	node *head,*tail,*p;
	head=new node;
	head->next=NULL;
	tail=head;//控制尾节点不断地移动。
	int n;
	scanf("%d",&n);
	while(n--)
	{
		p=new node;
		scanf("%d",&p->data);
		p->next=NULL;//保护
		tail->next=p;//i先右后左
		tail=p;
	}
	for(p=head->next;p!=NULL;p=p->next)
		printf("%d ",p->data);
return 0; 
}

然后就是逆序的
头插法:
把后建立的结点插在头部。用这种方法建立起来的链表的实际顺序与输入顺序刚好向反,输出时为倒序

#include<cstdio>
using namespace std;
struct node
{
	int data;
	node *next;
};
int main()
{
	node *head,*p;
	head=new node;
	head->next=NULL;
	int n;
	scanf("%d",&n);
	while(n--)
	{
		p=new node;
		scanf("%d",&p->data);
		p->next=head->next;//关键
		head->next=p;
	}
	for(p=head->next;p!=NULL;p=p->next)
		printf("%d ",p->data);
return 0; 
}

猜你喜欢

转载自blog.csdn.net/qq_43352073/article/details/88209025