编程实现对一个单向链表的结点进行反转,也就是将链表结点按逆序排列,排序后链头将成为链尾,而链尾将成为链头。自定义函数名称及函数功能要求如下: (1)定义“createNode”函数,实现创建一个新结点。 (2)定义“createList”函数,实现一个单向链表的创建。 ● 在创建结点时通过键盘输入为每个结点的数据成员value进行赋值。 ● 使用“头插法”将每个结点逐一插入到链表中。 (3)定义“display”的函数,实现对链表所有结点的遍历输出。 (4)定义“reverse”的函数,实现对链表结点的反转。 目前,已经编辑完成“createNode”函数、“createList”函数和“main”函数,请编程实现“display”函数和“reverse”函数。
时间: 2023-11-22 19:55:04 浏览: 60
以下是实现代码:
```c++
#include <iostream>
using namespace std;
struct Node {
int value;
Node* next;
};
Node* createNode(int value) {
Node* newNode = new Node;
newNode->value = value;
newNode->next = nullptr;
return newNode;
}
void createList(Node*& head) {
head = nullptr;
int value;
cout << "请输入链表结点的值,输入-1结束创建:" << endl;
cin >> value;
while (value != -1) {
Node* newNode = createNode(value);
newNode->next = head;
head = newNode;
cin >> value;
}
}
void display(Node* head) {
cout << "链表结点的值为:" << endl;
Node* cur = head;
while (cur != nullptr) {
cout << cur->value << " ";
cur = cur->next;
}
cout << endl;
}
void reverse(Node*& head) {
if (head == nullptr || head->next == nullptr) {
return;
}
Node* pre = nullptr;
Node* cur = head;
Node* post = nullptr;
while (cur != nullptr) {
post = cur->next;
cur->next = pre;
pre = cur;
cur = post;
}
head = pre;
}
int main() {
Node* head;
createList(head);
display(head);
reverse(head);
display(head);
return 0;
}
```
程序中,createList函数使用头插法逐一插入结点。display函数用于遍历输出链表结点的值。reverse函数使用三个指针pre、cur和post实现链表结点的反转。在main函数中,依次调用了createList、display和reverse函数。