C++ 实现单链表逆置:详细代码与示例
以下是一个使用 C++ 编写的逆置单链表的程序:
#include <iostream>
using namespace std;
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 创建链表
ListNode* createList(int n) {
ListNode* dummy = new ListNode(0);
ListNode* curr = dummy;
for (int i = 1; i <= n; i++) {
curr->next = new ListNode(i);
curr = curr->next;
}
return dummy->next;
}
// 打印链表
void printList(ListNode* head) {
while (head != NULL) {
cout << head->val << ' ';
head = head->next;
}
cout << endl;
}
// 逆置链表
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* curr = head;
while (curr != NULL) {
ListNode* nextTemp = curr->next;
curr->next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
int main() {
int n;
cout << '请输入链表的长度:';
cin >> n;
ListNode* head = createList(n);
cout << '原始链表: ';
printList(head);
ListNode* reversedHead = reverseList(head);
cout << '逆置后的链表: ';
printList(reversedHead);
return 0;
}
运行程序后,您需要输入链表的长度,然后程序会根据输入创建一个单链表。然后程序会打印原始链表,接着对链表进行逆置操作,并打印逆置后的链表。
原文地址: https://www.cveoy.top/t/topic/pbIE 著作权归作者所有。请勿转载和采集!