#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
int main()
{
struct node *head , *p , *q , *t;
int i , n , a;
void reverse(struct node *t);
scanf("%d",&n);
head = NULL;
for(i = 0;i < n;i++)
{
scanf("%d",&a);
p = (struct node *)malloc(sizeof(struct node));
p->data = a;
p->next = NULL;
if(head == NULL)
{
head = p;
}
else
{
q->next = p;
}
q = p;
}
t = head;
reverse(t);
printf("\n");
return 0;
}
//递归输出
void reverse(struct node *l)
{
if(l != NULL)
{
reverse(l->next);
printf("%d ",l->data);
}
}
确实好久没碰C语言了,感觉好生疏,本来数据结构的基础不是很好,现在可以趁机会补补数据结构了。
下面是将两个有序链表合并成一个有序链表 :
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
void input(struct node *p,int n);
void and_list(struct node *list1,struct node *list2);
void output(struct node *l);
int main()
{
int n;
struct node *p , *q;
p = (struct node *)malloc(sizeof(struct node));
q = (struct node *)malloc(sizeof(struct node));
p->next = NULL;
q->next = NULL;
printf("please input the number of the number in the first linklist : \n");
scanf("%d",&n);
input(p,n);
printf("please input the number of the number in the second linklist : \n");
scanf("%d",&n);
input(q,n);
and_list(p,q);
output(p);
printf("\n");
}
void input(struct node *p,int n)
{
struct node *temp , *end;
int i;
end = p;
for(i = 0;i < n;i++)
{
temp = (struct node *)malloc(sizeof(struct node));
scanf("%d",&temp->data);
end->next = temp;
temp->next = NULL;
end = temp;
}
}
void and_list(struct node *list1,struct node *list2)
{
struct node *p , *q , *temp;
p = list1;
q = list2->next;
while(p->next && q)
{
if(p->next->data > q->data)
{
temp = q->next;
q->next = p->next;
p->next = q;
q = temp;
}
else
{
p = p->next;
}
}
if(q)
{
p->next = q;
}
}
void output(struct node *list)
{
while(list->next)
{
printf("%d ",list->next->data);
list = list->next;
}
}