遍历一次将单链表反转
如题 求一成员函数, 自己初学者写了下, 问题太多了, 求个例子, 谢谢了
[解决办法]
假设root 为这个链表的头节点,current为当前位置的指针,preview 为当前位置前一个元素的指针,follow为后面的一个元素的指针,那么步骤如下:
preview = root;
current = root-> next;
follow = current-> next;
while(current != NULL){
current-> next = preview;
preview = current;
current = follow;
if(follow != NULL)
{
follow = current-> next;
}
}
//set the end
root-> next = NULL:
//set root as the head
root = preview;
[解决办法]
下面是单遍历链表倒置的一个测试小程序
#include <iostream>
using namespace std;
struct node
{
int data;
node*next;
};
void main()
{
//*****************************下面建立倒置的目标链表,存储数据1,2,3,4,5
node*headee=NULL;
node*p;
for(int i=1;i <=5;i++)
{
node*s=new node;
s-> data=i;
if(headee==NULL)headee=s;
else p-> next=s;
p=s;
}
p-> next=NULL;
node*m=headee;
while(m!=NULL)
{
cout < <m-> data < <endl;
m=m-> next;
}
//**********************************************************下面为插入头节点法倒置
node*head=NULL;
node*q=headee;
node*kao;
node *insert;
while(q)
{
kao=new node;
kao-> data=q-> data;
if(head==NULL){head=kao;head-> next=NULL;}
else
{
insert=kao;
insert-> next=head;
head=insert;
}
q=q-> next;
}
//***********************************************************
while(head)
{
cout < <head-> data < <endl;
head=head-> next;
}
}