单链表--就地逆置--C++实现

//以单链表作为存储结构,实现线性表的就地逆置。
#include
using namespace std;
struct Node
{
int data;
Node *next;
};
class LinkList {
public:
LinkList(int a[], int n);
~LinkList();
void inversion(Node *first);
Node *show(int n);
private:
Node *first, *s, *p;
};

//利用头插法定义一个单链表
LinkList::LinkList(int a[], int n)
{
first = new Node;
first->next = NULL;
for (int i = 0; i < n; i++)
{
s = new Node;
s->data = a[i];
s->next = first->next;
first->next = s;
}
}
// Destructor
LinkList::~LinkList()
{
Node *d;
while (first != NULL)
{
d = first;
first = first->next;
delete d;
}
}
void LinkList::inversion(Node *first)
{
Node *k, *q, *r;
k = first->next;
q = k->next;
r = first->next;
while (true)
{
if (q->next == NULL)
{
first->next = q;
q->next = r;
k->next = NULL;
break;
}
else
{
first->next = q;
k->next = q -> next;
q->next = r;
q = k->next;
r = first->next;
}
}
}
Node *LinkList::show(int n)
{
//define a pointer p of Node to save first location
Node *q;
q = first->next;
for (int i = 0;i < n;i++)
{
cout << q->data;
q = q->next;
}
return first;
}
int main()
{
int n;
int a[100];
cout << “how many number you will input?” << endl;
cin >> n;
cout << “input the number of the narry:” << endl;
for (int i = 0;i < n;i++)
{
cin >> a[i];
}

LinkList link = LinkList(a, n);

cout << "The sequence before the reverse sequence is:" << endl;
Node *f=link.show(n);
cout << endl;
link.inversion(f);
cout << "The sequence after the reverse sequence is:" << endl;
Node *t = link.show(n);
cout << endl;
system("pause");
return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值