编写一个函数, 给定一个链表的头指针,要求只遍历一次, 将单链表中的元素顺序翻转过来

时间:2021-10-07 11:03:02
#include<iostream>  
using namespace std;  


struct Node{  
int data;  
Node* next;  
};  


int a[9]={1,2,3,4,5,6,7,8,9};  


int main(){  
Node *head;  
head=(Node *)malloc(sizeof(Node));  
head->next=NULL;  
for(int i=0;i<9;i++){  
Node *tmp=(Node *)malloc(sizeof(Node));  
tmp->data=a[i];  
tmp->next=head->next;  
head->next=tmp;  
}  
for(Node *tmp=head->next;tmp;tmp=tmp->next)  
cout<<tmp->data<<" ";  
cout<<endl;  
Node* pcurrent,*pnext,*pnnext;  
pcurrent=(Node *)malloc(sizeof(Node));  
pnext=(Node *)malloc(sizeof(Node));  
pnnext=(Node *)malloc(sizeof(Node));  


pcurrent=head->next;  
pnext=pcurrent->next;  
pnnext=pnext->next;  
int n=0;  
while(pnnext!=NULL){  
n++;  
if(n==1)  
  pcurrent->next=NULL;  
pnext->next=pcurrent;  
pcurrent=pnext;  
pnext=pnnext;  
pnnext=pnnext->next;  
}  
pnext->next=pcurrent;  
head->next=pnext;  


for(Node *tmp=head->next;tmp;tmp=tmp->next)  
cout<<tmp->data<<" ";  
system("pause"); return 0;


}