问题:如何实现一个高效的单向链表逆序输出?
# 下面是其中一种写法,也可以有不同的写法,比如递归等。供参考。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
typedef struct node{
int data;
struct node* next;
node(int d):data(d), next(NULL){}
}node;
void reverse(node* head)
{
if(NULL == head || NULL == head->next){
return;
}
node* prev=NULL;
node* pcur=head->next;
node* next;
while(pcur!=NULL){
if(pcur->next==NULL){
pcur->next=prev;
break;
}
next=pcur->next;
pcur->next=prev;
prev=pcur;
pcur=next;
}
head->next=pcur;
node*tmp=head->next;
while(tmp!=NULL){
cout<<tmp->data<<"\t";
tmp=tmp->next;
}
}