单链表的就地逆置c++
时间: 2024-06-13 15:08:58 浏览: 16
以下是单链表的就地逆置C++代码实现:
```c++
#include <iostream>
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 = n - 1; i >= 0; i--) {
s = new Node;
s->data = a[i];
s->next = first->next;
first->next = s;
}
}
LinkList::~LinkList() {
while (first ! NULL) {
p = first;
first = first->next;
delete p;
}
}
void LinkList::inversion(Node *first) {
Node *p, *q;
p = first->next;
first->next = NULL;
while (p != NULL) {
q = p->next;
p->next = first->next;
first->next = p;
p = q;
}
}
Node *LinkList::show(int n) {
p = first->next;
for (int i = 0; i < n && p != NULL; i++) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
return first;
}
int main() {
int a[] = {1, 2, 3, 4, 5};
LinkList L(a, 5);
cout << "原链表:";
L.show(5);
L.inversion(L.show(5));
cout << "逆置后的链表:";
L.show(5);
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)