链表反转-带头指针

链表分为两种,一种有头指针,头指针没有值只存储地址,一种是不带头指针的,第一个节点即为实际第一点,有值。

下面的代码为带头指针的链表反转。

#include <assert.h>
#include <stdio.h>
#include <iostream>
using namespace std;

typedef struct node
{
	int data;
	node* next;
};
//建立链表  
node* create_link( int*  array ,int length)  
{  
	 node* phead = new node();     //带有表头的链表,表头中不存储任何元素  
	 node* preNode = phead;  
	for( int i=0; i<length; i++ )  
	{  
		struct node * pNode = new node();  
		pNode->data = array[i];  
		pNode->next = NULL;  
		preNode->next = pNode;  
		preNode = pNode;  
	}  
	return phead;  
} 
//输出链表  
void out_link( node* phead )  
{  
	if( phead == NULL )  
		return;  
	struct node * pNode = phead->next;  
	while( pNode )  
	{  
		cout <<pNode->data;  
		pNode = pNode->next;  
	}  
	cout << endl;  
}  

node* reverse_linktable(node* phead)
{
	assert(NULL!=phead&&NULL!=phead->next);
	node *pre,*cur,*next;
	cur=phead->next;
	pre=NULL;//开始时pre为空
	while(cur!=NULL)
	{
		next=cur->next;
		cur->next=pre;
		pre=cur;
		cur=next;
	}
	phead->next=pre;
	return phead;
}
void test()
{
	int array[]={5,2,4,7,8,1,3,9,6,0};
	node *phead=create_link(array,10);
	cout<<"反转前链表:";
	out_link(phead);
	cout<<"反转后链表:";
	node *pphead=reverse_linktable(phead);
	out_link(pphead);

}
int main()
{
	test();
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值