就地逆置:
如果要实现链表的就地逆置,可以定义两个新的指针——一个前驱指针prev和一个后继指针latter,刚开始时,prev是置空的,单列一个临时指针p,p开始时指向初始链表的第一个数据域不为空的节点,latter始终指向p的下一个节点;逆序开始时,将让p的next指向prev,然后让prev指向p,p和latter分别向后顺延一位(先让p顺延,当p不为空时,才让latter指向p的下一节点),如此循环之到链表逆序完成。
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct Node{
int data;
struct Node* next;
}node;
node* CreatList(){
node* head=new node;
head->next=NULL;
node* last=head;
int n;
cin>>n;
int num;
for(int i=0;i<n;i++){
cin>>num;
node* p=new node;
p->data=num;
p->next=NULL;
last->next=p;
last=p;
}
return head;
}
void NiXu_List(node* head){
node *p,*prev,*latter;
p=head->next;
prev=NULL;
latter=p->next;
while(p!=NULL){
p->next=prev;
prev=p;
p=latter;
if(p!=NULL)
latter=p->next;
}
head->next=prev;
}
void PrintList(node* head){
for(node* p=head->next;p;p=p->next){
cout<<p->data<<" ";
}
}
int main(){
node* head=CreatList();
NiXu_List(head);
PrintList(head);
return 0;
}