反转单链表

#include <iostream>
using namespace std;

typedef struct node
{
	int value;
	struct node* next;
	node(){next=NULL;}
	node(int v,node* n){value=v;next=n;}
}node;

void insert(node*& head,int a[],int n)//??????????????????注意要用引用
{
	node* rear=NULL;
	for(int i=0;i<n;i++)
	{
		if(!head)
			rear=head=new node(a[i],NULL);
		else
			rear=rear->next=new node(a[i],NULL);
	}
}

node* reverse(node* head)
{
	if(head){
		node* p1=head,*p2,*p3,*temp;// 1 2 3 4 5 6 7 8 9 0, p1->1,p2->2, p3保存p2下一个节点的位置,每循环一个,p1指向p3在开始,而p1这次应该指向上次循环的p2
// 保存为temp; while(1) { p2=p1->next; if(!p2) break; p3=p2->next; p2->next=p1; if(p1==head) p1->next=NULL; else { p1->next=temp; } if(p3) p1=p3; else return p2;//我草,当p3==null时,p1就为null了,不能在循环了,直接返回p2 temp=p2; } return p1; } else{ return NULL;} } int main() { int a[10]={1,2,3,4,5,6,7,8,9,0}; node* head=NULL; insert(head,a,10); node* head2=reverse(head); while(head2) { cout<<head2->value<<" "; head2=head2->next; } return 0; }

  

转载于:https://www.cnblogs.com/shuguang/archive/2012/12/04/2802300.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值