C++ 单链表的 就地逆置 ,以及基本操作

#include "stdafx.h"
#define  sub(a,b) a-b //没用
#include <iostream>
using namespace std;
struct node
{
	int a;
	node * next;
};
int _tmain(int argc, _TCHAR* argv[])
{
	//int x=sub(3,8);
  
     node * createList();
	cout<<"开始创建链表"<<endl;
	node *pbeg=createList();
	node *p=pbeg;
	while (p)
	{
		cout<<"本节点数值是:"<<p->a<<endl;
		p=p->next;
	}
	cout<<"请输入要删除的元素"<<endl;
	int loc;
	cin>>loc;
	node * delEle(node * pbeg,int loc);
	node * ru;
	ru=delEle(pbeg,loc);
	cout<<"删除元素后的链表的遍历结果"<<endl;
	while (ru)
	{
		cout<<"本节点数值是:"<<ru->a<<endl;
		ru=ru->next;
	}

	node * rt(node * pbeg);//声明函数
	node * r=rt(pbeg);
	cout<<"变为逆序后的链表的遍历结果"<<endl;
	while (r)
	{
		cout<<"本节点数值是:"<<r->a<<endl;
		r=r->next;
	}
	return 0;
}

//使单链表变为原来的逆序
node * rt(node * pbeg)
{
	node * pPre=pbeg;
	node * pCur=pPre->next;
	node * pNext=NULL;

	while(pCur)
	{
		pNext=pCur->next;
		pCur->next=pPre;
		pPre=pCur;
		pCur=pNext;
	}
	pbeg->next=NULL;
	return pPre;//返回新的表头节点
}
//创建单链表
node * createList()
{
	node * pbeg=new node;
	(*pbeg).a=1;
	node * p=pbeg;
	int j=9;
	node * q;
	while(j>0)
	{
		j--;
		q=new node;
		cout<<"请输入一个整数"<<endl;
		int temp;
		cin>>temp;
		q->a=temp; //赋值

		p->next=q;
		p=q;
	}
	p->next=NULL;
	return pbeg;
}
//删除指定元素的节点;
node * delEle(node * pbeg,int ele)
{
	node * pPre=pbeg;
	node *pCur=pbeg->next;

	if (pbeg->a==ele)
		pbeg=pbeg->next;
	else
	{
		while (pCur->a!=ele&&pCur)
		{
			pPre=pCur;
			pCur=pCur->next;
		}
		pPre->next=pCur->next;
	}
	return pbeg;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值