单链表的逆置
将单链表逆置: 定义一个前指针和一个后指针用来辅助工作指针
#ifndef LINKLIST_H_INCLUDED
#define LINKLIST_H_INCLUDED
struct Node{
int data;
Node *next;
};
class LinkList{
public:
LinkList(int *arr,int n);
~LinkList();
void printList();
void inverseList();
private:
Node *first;
};
#endif
#include "LinkList.h"
#include <iostream>
using namespace std;
LinkList::LinkList(int *arr,int n){
first=new Node;
Node *s=NULL;
first->data=arr[0];
Node *rear=first;
for(int i=1;i<n;i++){
s=new Node;
s->data=arr[i];
rear->next=s;
rear=s;
}
rear->next=NULL;
}
LinkList::~LinkList(){
Node *p=first;
while(p){
first=first->next;
delete p;
p=first;
}
}
void LinkList::printList(){
Node *p=first;
while(p){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
void LinkList::inverseList(){
Node *pre=NULL;
Node *rear=first;
Node *p=first;
while(p){
rear=rear->next;
p->next=pre;
pre=p;
p=rear;
}
first=pre;
}
|