http://blog.csdn.net/niuer09/article/details/5961004 (关于逆序的详细介绍)
void reserve(list_node* phead)
{
list_node * p = phead->next;
if(p == NULL || p->next == NULL)
return; //只有头节点或一个节点
list_node* p1=p->next;
p->next=NULL;
while(p1!=NULL)
{
p = p1->next;
p1->next = phead->next;
phead->next = p1;
p1 = p;
}
}
#include<iostream>
using namespace std ;
typedef struct node
{
char data ;
struct node * next ;
}node , *List ;
/*创建链表*/
void CreateList(List &L)
{
L = (node *)malloc(sizeof(node));
L->next = NULL ;
}
/*插入数据到链表*/
void InsertList(List &L , int pos , char e )
{
List p ;
p = L ;
int j = 0 ;
while( p && j < pos - 1) //找到链表中pos的位置
{
p = p ->next ;
j ++ ;
}
if(!p || j > pos - 1 ) //当i的位置小于1或则大于表长
{
cout <<"pos wrong "<<endl;
return ;
}
List s ; //创建一个节点s,用来做为插入点
s= (node * )malloc(sizeof(node)) ;
s->data = e;
s->next = p->next ;
p->next = s ;
}
/*输出数据*/
void outprint(char e)
{
cout << e ;
}
/*遍历链表*/
void TraList(List L)
{
List p=L->next ;
while(p)
{
outprint(p->data);
p = p ->next ;
}
}
/*将链表逆序*/
void Reserve(List &L)
{
if(!L->next || !L->next->next) //当只有一个元素或则为空表时,直接返回
return ;
List p= L->next , q = p->next ,t;
while(q)
{
t = q->next ;
q->next = p;
p = q ;
q = t ;
}
L->next->next = NULL ;
L->next = p;
}
/*从链表中删除数据*/
char DeleteList(List &L, int pos)
{
List p = L;
int j = 0 ;
while(p->next && j<pos -1)
{
p = p->next ;
j ++;
}
if(!p->next || j>pos-1) //删除的位置小于1或则超出表长
{
cout<<"pos wrong"<<endl;
return -1;
}
char e = p->next->data ;
List q = p->next ;
p->next = q->next ;
free(q);
return e ;
}
int main(void)
{
List L ;
L = (node *)malloc(sizeof(node)) ;
CreateList(L);
char e ;
int j ;
cout<<"插入数据"<<endl;
for( int i = 0 ; i < 10 ; i ++){
e = 'A' + i ;
j = 1 ;
InsertList(L , j , e ) ;
}
TraList(L);
cout<<endl ;
cout<<"链表逆序"<<endl;
Reserve(L);
TraList(L);
cout<<endl;
cout <<"删除数据:(输入0时结束)"<<endl;
while(cin>>j && j){
char e = DeleteList(L,j);
cout<<"删除的数据是:"<<e<<endl;
TraList(L);
cout<<endl;
}
return 0;
}