问题:
给出一个链表,将其逆序并打印出来。这是一道面试题,当时脑残没想起来,现在写一个原地逆序的方法,非常easy,代码如下:
#include<cstdio>
#include<cstdlib>
#define ERROR -1
typedef struct NODE
{
int data;
struct NODE *next;
}NODE,*LNODE;
int main()
{
int i,j;
int n;
LNODE head=(LNODE)malloc(sizeof(NODE));
LNODE p,q,temp;
LNODE tail;
head->next=NULL;
tail=head;
scanf("%d",&n);
for(i=0;i<n;i++)
{
p=(LNODE)malloc(sizeof(NODE));
if(!p)
return ERROR;
scanf("%d",&(p->data));
p->next=NULL;
tail->next=p;
tail=p;
}
p=head->next;
temp=p->next;
while(p&&temp)
{
q=temp;
temp=temp->next;
q->next=p;
if(p==head->next)
{
p->next=NULL;
}
p=q;
}
head->next=p;
q=head->next;
while(q)
{
printf("%d ",q->data);
q=q->next;
}
return 0;
}