插入法单链表的逆序代码

本文介绍了如何使用C++语言通过插入法来创建单链表,并展示了如何对其进行逆序操作。包括链表的创建、显示、逆序过程的详细步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <vector>
#include <string>
#include <strstream>
#include <time.h>
using namespace std;

struct mynode{
	int data;
	 mynode* next;
};
void  myreverse(mynode* phead)
{	
		 mynode* h =((mynode*)phead)->next;
		mynode *p1=h;
		 mynode *p2=h->next;
		 mynode *p3=h->next->next;
	while(p2->next)
	{	
		//在头结点和成功逆序队列之间进行插入
	//	cout<<"the while"<<p2->data<<"   "<<p3->data<<endl;
		
		p2->next=((mynode*)phead)->next;
		phead->next=p2;
		p1->next=p3;
		p2=p3;
		p3=p3->next;
		
	}	

	p2->next=((mynode*)phead)->next;
		phead->next=p2;
		p1->next=p3;
}
void show(mynode* p)
{
	for(int i=0;i<10;i++)
	{	p=p->next;	
		cout<<i<<" : "<<p->data<<endl;
	}
}
void create(mynode *phead)
{
	mynode* p;
for(int i=0;i<10;i++)
	{
		p=(mynode*)malloc(sizeof(mynode));
		p->data=rand()%100+1;
		p->next=(*phead).next;
		(*phead).next=p;
	}
}
int main ()
{	
	mynode *phead;
	srand(time(0));
	phead=(mynode*)malloc(sizeof(mynode));
	(*phead).next=NULL;
	
	create(phead);
	
	show(phead);

	cout<<endl;
	cout<<"revers :"<<endl;
	myreverse(phead);

	cout<<"presult"<<endl;
	show(phead);


	return 0; 
}



//插入法进行单链表创建,并且插入法逆序单链表


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值