顺序建立链表
逆序建立链表
#include<bits/stdc++.h>
struct node
{
int data;
struct node *next;
};
struct node *creat(int n)///顺序建立链表
{
struct node *head,*p,*tail;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(int i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
return head;
}
struct node *creat2(int n)///逆序建立链表
{
struct node *head,*tail,*q;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head->next;
for(int i=1;i<=n;i++)
{
q=(struct node *)malloc(sizeof(struct node));
q->next=NULL;
scanf("%d",&q->data);
q->next=tail;
head->next=q;
tail=q;
}
return head;
}
void display(struct node *head)///遍历链表
{
struct node *q;
q=head->next;
while(q!=NULL)
{
if(q->next==NULL)
printf("%d\n",q->data);
else
printf("%d “,q->data);
q=q->next;
}
}
int main()
{
struct node *head;
int n;
scanf(”%d",&n);
head=creat2(n);
display(head);
return 0;
}