链表学习
一些学习中的探索
输入n,表示要输入n个数,输入n个数,建链表,用链表的方法输出n个数
顺序输出
#include<stdio.h>
#include<stdlib.h>
void prn(struct node *head);
struct node{
int data;
struct node *next;
};
struct node *p,*head;
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
head=NULL;//这种head是一直等于链表的第一个元素而不是作为一个标志指针指向第一个元素
while(n--)
{ //强转
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=head;
head=p; //头插法
} //链表已经建好
prn(head); //用递归函数输出链表
}
return 0;
}
void prn(struct node *head)
{
if(head==NULL)
{
return ;
}
prn(head->next); //用小秘书取找更小的秘书
printf("%d ",head->data); //逆着链表输出
}
逆序输出:
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
}*head,*p; //注意head是指针
void prn(struct node *head)
{
while(head)
{
printf("%d ",head -> data);
head = head -> next;
}
}
int main()
{
int n;
scanf("%d",&n);
head = NULL;
while(n--)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next = head;
head = p;
}
prn(head);
return 0;
}
改良版:
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node * next;
}*head,*p;
void input(int n)
{
int i;
for(i = 0; i < n; i++)
{
p = (struct node *)malloc(sizeof(struct node));
scanf("%d",&p -> data);
p -> next = head;
head = p;
}
}
void order_output(struct node *head)
{
if(head == NULL)
return ;
order_output(head -> next); //用递归来顺序输出
printf("%d ",head -> data);
}
void reverse_output(struct node *head)
{
while(head)
{
printf("%d ",head -> data);
head = head -> next;
}
}
int main()
{
int n;
head = NULL;
scanf("%d",&n);
input(n);
printf("\n");
order_output(head);
printf("\n");
reverse_output(head);
return 0;
}