湛江做网站哪家好,网站建设费用主要包括哪些方面,wordpress建立网站实例,西安专业做网站文章目录 1.原题2.算法思想3.关键代码4.完整代码5.运行结果 1.原题
为带表头的单链表类Chain编写一个成员函数Reverse#xff0c;该函数对链表进行逆序操作#xff08;将链表中的结点按与原序相反的顺序连接#xff09;#xff0c;要求逆序操作就地进行#xff0c;不分配… 文章目录 1.原题2.算法思想3.关键代码4.完整代码5.运行结果 1.原题
为带表头的单链表类Chain编写一个成员函数Reverse该函数对链表进行逆序操作将链表中的结点按与原序相反的顺序连接要求逆序操作就地进行不分配任何新的结点。要求首先给出类的声明在类的声明中其它成员函数省略。
2.算法思想
定义三个指针变量*prevNode、*currentNode、*nextNode在遍历过程中反指。对第一个元素和最后一个的元素处理略有不同需要单独处理。
3.关键代码
/*** struct ListNode* brief 单链表中的节点结构。*/
struct ListNode {int data; /** 节点中存储的数据 */struct ListNode *next; /** 指向下一个节点的指针 */
};/*** struct List* brief 单链表结构。*/
struct List {struct ListNode *head; /** 指向链表头节点的指针 */int size; /** 链表的大小 */
};/*** brief 反转链表中的元素。* param list 指向 List 结构的指针。*/
void Reverse(struct List *list) {struct ListNode *prevNode NULL, *currentNode list-head-next, *nextNode NULL;while (currentNode ! NULL) {nextNode currentNode-next; // 存储下一个节点currentNode-next prevNode; // 反转指向前一个节点的指针prevNode currentNode; // 移动指针以进行下一次迭代currentNode nextNode;}list-head-next prevNode; // 更新头指针使其指向反转后的新的第一个节点
}4.完整代码
/*** file main.c* brief 实现了单链表及其反转操作。*/#include stdio.h
#include stdlib.h/*** struct ListNode* brief 单链表中的节点结构。*/
struct ListNode {int data; /** 节点中存储的数据 */struct ListNode *next; /** 指向下一个节点的指针 */
};/*** struct List* brief 单链表结构。*/
struct List {struct ListNode *head; /** 指向链表头节点的指针 */int size; /** 链表的大小 */
};/*** brief 反转链表中的元素。* param list 指向 List 结构的指针。*/
void Reverse(struct List *list) {struct ListNode *prevNode NULL, *currentNode list-head-next, *nextNode NULL;while (currentNode ! NULL) {nextNode currentNode-next; // 存储下一个节点currentNode-next prevNode; // 反转指向前一个节点的指针prevNode currentNode; // 移动指针以进行下一次迭代currentNode nextNode;}list-head-next prevNode; // 更新头指针使其指向反转后的新的第一个节点
}/*** brief 显示链表中的元素。* param list 指向 List 结构的指针。*/
void displayList(struct List *list) {struct ListNode *currentNode list-head-next;printf(head);while (currentNode ! NULL) {printf(-%d, currentNode-data);currentNode currentNode-next;}printf(-NULL\n);
}/*** brief 主函数展示链表操作。* return 程序退出状态。*/
int main() {struct List list;list.head (struct ListNode *) malloc(sizeof(struct ListNode));list.head-next NULL;list.size 0;// 插入初始元素 1, 2, 3, 4, 5for (int i 1; i 5; i) {struct ListNode *newNode (struct ListNode *) malloc(sizeof(struct ListNode));newNode-data i;newNode-next list.head-next;list.head-next newNode;list.size;}// 输出原始链表printf(Original List: );displayList(list);// 执行反转操作Reverse(list);// 输出反转后的链表printf(Reversed List: );displayList(list);return 0;
}
5.运行结果