利用三個額外的節點指針修改鏈表節點的指向
詳細參考Reverse函數
[cpp]
// 倒排鏈表節點.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
typedef struct node
{
int data;
node *next;
}Node;
class SList
{
public:
SList();
~SList();
void Print();
void CreateList(int *start,int *end);
void Reverse();
private:
Node *head;
};
SList::SList()
{
head=NULL;
}
SList::~SList()
{
Node *p;
while(head!=NULL)
{
p=head;
head=head->next;
delete p;
}
}
void SList::CreateList(int *start,int *end)
{
head=new Node;
head->next=NULL;
Node *ptmp;
head->data=*start;
if(start==end)
return;
else
start++;
while(start!=end)
{
ptmp=new Node;
ptmp->next=head;
ptmp->data=*start;
head=ptmp;
start++;
}
}
void SList::Reverse()
{
Node *first,*mid,*last;
first=head;
mid=head->next;
while(mid!=NULL)
{
last=mid->next;
mid->next=first;
first=mid;
mid=last;
}
head->next=NULL;
head=first;
}
void SList::Print()
{
Node *p=head;
int i=1;
while(p!=NULL)
{
cout<<"第"<<i<<"個節點:"<<p->data<<endl;
p=p->next;
i++;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
SList list;
int arr[]={10,9,8,7,6,5,4,3,2,1};
list.CreateList(arr,arr+10);
list.Print();
list.Reverse();
cout<<"逆序後:"<<endl;
list.Print();
system("pause");
return 0;
}
// 倒排鏈表節點.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
typedef struct node
{
int data;
node *next;
}Node;
class SList
{
public:
SList();
~SList();
void Print();
void CreateList(int *start,int *end);
void Reverse();
private:
Node *head;
};
SList::SList()
{
head=NULL;
}
SList::~SList()
{
Node *p;
while(head!=NULL)
{
p=head;
head=head->next;
delete p;
}
}
void SList::CreateList(int *start,int *end)
{
head=new Node;
head->next=NULL;
Node *ptmp;
head->data=*start;
if(start==end)
return;
else
start++;
while(start!=end)
{
ptmp=new Node;
ptmp->next=head;
ptmp->data=*start;
head=ptmp;
start++;
}
}
void SList::Reverse()
{
Node *first,*mid,*last;
first=head;
mid=head->next;
while(mid!=NULL)
{
last=mid->next;
mid->next=first;
first=mid;
mid=last;
}
head->next=NULL;
head=first;
}
void SList::Print()
{
Node *p=head;
int i=1;
while(p!=NULL)
{
cout<<"第"<<i<<"個節點:"<<p->data<<endl;
p=p->next;
i++;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
SList list;
int arr[]={10,9,8,7,6,5,4,3,2,1};
list.CreateList(arr,arr+10);
list.Print();
list.Reverse();
cout<<"逆序後:"<<endl;
list.Print();
system("pause");
return 0;
}