将链表中的节点顺序倒排序
利用三个额外的节点指针修改链表节点的指向
详细参考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;
}
补充:软件开发 , C++ ,