问题: 给出一个时间的非递归过程,实现对一个含n个元素的单链表的逆转
思路:逆转即把结点的next指针指向前一个结点,在做逆转的时候要先储存下之前的next指向的值。
逆转后的表头为之前单链表的最后一个元素。
代码:
#include<iostream>
using namespace std;
//先实现一个单链表(为了强化对链表的理解)
struct Node
{
Node * next;
int value;
Node(int v):next(NULL),value(v){};
};
struct SingleList
{
Node * head;
SingleList():head(NULL){};
};
void Insert(SingleList * lst, int n)
{
Node *nd=new Node(n);
nd->next=lst->head;
lst->head=nd;
}
int Delete(SingleList * lst, Node * n)
{
if (lst->head==NULL)
{
cout<<"error"<<endl;
return NULL;
}
if(lst->head==n)
{
lst->head=NULL;
int y=lst->head->value;
delete n;
return y;
}
Node *p=lst->head;
Node *q=lst->head->next;
while(q!=NULL)
{
if(q==n)
{
p->next=q->next;
int x=q->value;
delete n;
return x;
}
p=q;
q=p->next;
}
cout<<"no such node"<<endl;
return NULL;
}
void Print(SingleList * lst)
{
Node *p=lst->head;
while(p!=NULL)
{
cout<<p->value<<" ";
p=p->next;
}
cout<<endl;
}
//单链表的逆转
void Reverse(SingleList * lst)
{
if(lst->head==NULL)
cout<<"error"<<endl;
else
{
Node *p=lst->head;
Node *q=lst->head->next;
Node *r;
while(q!=NULL)
{
r=q->next;
q->next=p;
p=q;
q=r;
}
lst->head->next=NULL;
lst->head=p;//注意这里是p
}
}
int main()
{
SingleList * lst=new SingleList;
for(int i=0;i<5;i++)
Insert(lst, 2*i);
Print(lst);
Delete(lst,lst->head->next);
Print(lst);
Reverse(lst);
Print(lst);
delete lst;
return 0;
}