逆置单链表
建立长度为n的单链表,然后将其数据元素逆置,即第1个元素变为最后一个元素,第2个元素变为倒数第2个元素,以此类推,最后一个元素变为第1个元素。(处理的数据类型为字符型。必须使用链表完成。)
输入
第一行为链表长度n; 第二行为链表中的n个数据元素的值。
输出
逆置后的原始的值。
样例输入
10 ABCDEFGHIJ
样例输出
J I H G F E D C B A
#include<stdio.h>
#include<malloc.h>
struct LinkNode
{
char data;
struct LinkNode *next;
};
struct LinkNode *CreateList(int n)
{
char a;
struct LinkNode *head,*p1,*p2;
head=p1=(struct LinkNode*)malloc(sizeof(struct LinkNode));
scanf("%c",&a);
scanf("%c",&p1->data);
for(int i=1;i<n;i++)
{
p2=(struct LinkNode*)malloc(sizeof(struct LinkNode));
p1->next=p2;
p1=p2;
scanf("%c",&p1->data);
}
p1->next=NULL;
return head;
}
void ReverseList(struct LinkNode *&head)
{
struct LinkNode *p1,*p2,*p3;
p1=head;
p2=p1->next;
while(p2!=NULL)
{
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
head->next=NULL;
head=p1;
}
int main()
{
int n;
struct LinkNode *head,*p;
scanf("%d",&n);
head=CreateList(n);
ReverseList(head);
p=head;
while(p!=NULL)
{
printf("%c ",p->data);
p=p->next;
}
}
/*
#include<stdio.h>
int main()
{
int n;
char a[100];
scanf("%d",&n);
scanf("%s",a);
for(int i=n-1;i>=0;i--)
printf("%c ",a[i]);
}
*/