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

来源:互联网 发布:淘宝大学新手入门 编辑:程序博客网 时间:2024/06/03 23:28
#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;}

0 0
原创粉丝点击