数据结构实验之链表一:顺序建立链表
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
int n, i;
scanf("%d", &n);
struct node *head, *tail, *p;
head = (struct node *)malloc(sizeof(struct node));
tail = head;
for(i = 0; i < n; i++ )
{
p = (struct node *)malloc(sizeof(struct node));
scanf("%d", &p ->data);
p ->next = NULL;
tail ->next = p;
tail = p;
}
p = head ->next;
while(p)
{
if(p)
printf("%d ", p ->data);
else
printf("%d\n", p ->data);
p = p ->next;
}
return 0;
}
数据结构实验之链表二:逆序建立链表
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
int n, i;
scanf("%d", &n);
struct node *head, *p;
head = (struct node *)malloc(sizeof(struct node));
head ->next = NULL;
for(i = 0; i < n; i++ )
{
p = (struct node *)malloc(sizeof(struct node));
scanf("%d", &p ->data);
p ->next = head ->next;
head ->next = p;
}
p = head ->next;
while(p)
{
if(p)
printf("%d ", p ->data);
else
printf("%d\n", p ->data);
p = p ->next;
}
return 0;
}