核心算法:
利用链表的删除和头插法,实现链表的倒序输出(主文件中)
头文件:
myLink.h
#include<iostream>
struct Node
{
int data;
Node *next;
};
class myLink
{
public:
myLink();
Node *head;
void creatLinkLast(int a);
void printLink();
void delHead();
void getHead(Node *&t);
};
myLink.cpp
#include<iostream>
#include"myLink.h"
using namespace std;
myLink::myLink()
{
head=new Node;
head->next=head;
}
//初始化链表
void myLink::creatLinkLast(int a)
{
Node *p;
if(head->next==head) //链表为空时
{
p=new Node;
p->data=a;
head->next=p;
p->next=head;
}
else //链表不为空时
{
p=head;
while(p->next!=head)
{
p=p->next;
}
Node *q=new Node;
q->data=a;
p->next=q;
q->next=head;
}
}
//返回头节点
void myLink::getHead(Node *&t)
{
t=head;
}
//释放头结点
void myLink::delHead()
{
delete head;
}
//输出链表的所有内容
void myLink::printLink()
{
Node *p;
getHead(p);
while(p->next!=head)
{
p=p->next;
cout<<p->data<<" ";
}
cout<<" "<<endl;
}
主文件
#include <iostream>
#include"myLink.h"
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
//链表的倒置
bool reLink(myLink &a,myLink &b)
{
Node *headA,*headB,*pb,*pa;
a.getHead(headA);
b.getHead(headB);
if(headA->next==headA)
return false;
else
{
while(headA->next!=headA)
{
pa=headA->next;
pb=headB->next;
headB->next=pa;
headA->next=headA->next->next;
headB->next->next=pb;
}
a.delHead();
return true;
}
}
int main() {
myLink ma;
myLink bb;
ma.creatLinkLast(3);
ma.creatLinkLast(5);
ma.creatLinkLast(4);
ma.creatLinkLast(6);
ma.creatLinkLast(7);
ma.printLink();
if(reLink(ma,bb))
{
cout<<"倒置后链表为:";
bb.printLink();
}
else
cout<<"输入链表为空";
return 0;
}
运行结果