本算法复杂度为O(n)
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
typedef struct A{
int X;
A *next;
}A;
using namespace std;
A *input (A *head)//链表输入,输入0时结束。
{
A *p;
A *q;
int n;
p=NULL;
q=NULL;
scanf(“%d”,&n);
while(n>0)
{
p=(A *)malloc(sizeof(A));
p->X=n;
p->next=NULL;
if (head==NULL)
{
head=(A *)malloc(sizeof(A));
head=p;
}
else
q->next=p;
q=p;
scanf(“%d”,&n);
}
return head;
}
void print(A *head)
{
A *p;
p=head;
while(p!=NULL)
{
printf(“%d “,p->X);
p=p->next;
}
printf(“\n”);
}
A *A_reverse(A *head)//链表逆序
{
A *p;
A *q;
A *temp;
q=NULL;
temp=NULL;
p=head;
q=p->next;
while(p->next!=NULL)
{
temp=q->next;
q->next=p;
if (p==head)
{
p->next=NULL;
}
p=q;
if (temp!=NULL)
q=temp;
else
break;
}
head=q;
return head;
}
int main()
{
A *head;
head=NULL;
head=input(head);
print(head);
head=A_reverse(head);
print(head);
return 0;
}