#include <iostream>
using namespace std;
struct node
{
int data;
struct node *next;
};
**//尾插法构建不带头结点的单链表**
struct node * creat_wf(int n)
{
struct node *head;
struct node *p,*q;
head = NULL;
for(int i=0;i<n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
cin>>p->data;
if(head == NULL)
head = p;
else
q->next = p;
q=p;
}
q->next = NULL;
return head;
}
**//尾插法构建带头结点的单链表**
struct node * creat_wt(int n)
{
struct node *head;
struct node *p,*q;//尾插法中必须有一个尾指针始终指向当前链表的尾结点
//创建头结点
**//****头结点的作用:①在链表第一个位置上的操作和其他位置一样,不需要进行特殊处理 ②无论链表是否为空,其头指针都是指向头结点的非空指针,因此空表和非空表的处理统一**
p=(struct node *)malloc(sizeof(struct node));
cin>>p->data;
head=p;
//构建其他结点
for(int i=1;i<n;i++)
{
q=(struct node *)malloc(sizeof(struct node));
cin>>q->data;
p->next = q;
p=q;
}
p->next = NULL;
return head;
}
**//头插法构建单链表**
struct node * creat_t(int n)
{
struct node *head;
struct node *p;
head=NULL;
for(int i=0;i<n;i++)
{
p=(struct node *)malloc(sizeof(struct node));//生成新的结点
cin>>p->data;
p->next=head;
head=p;
}
return head;
}
**//输出链表**
void out_l(struct node *head)
{
struct node *h=head;
while(h)
{
cout<<h->data<<endl;
h=h->next;
}
}
int main()
{
int n;
cin>>n;
struct node *head=creat_wt(n);
out_l(head);
struct node *head1=creat_t(n);
out_l(head1);
struct node *head2=creat_wt(n);
out_l(head2);
return 0;
}
单链表的构建
猜你喜欢
转载自blog.csdn.net/gyhjlauy/article/details/89184418
今日推荐
周排行