链式链表的相关操作+删除+添加+逆序+遍历

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值