C++实现带头结点单链表基本操作:求表长、定位和插入
#include <iostream>
using namespace std;
// 定义链表结点
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
// 求表长
int getLength(ListNode* head) {
int length = 0;
ListNode* p = head->next;
while (p != nullptr) {
length++;
p = p->next;
}
return length;
}
// 定位
ListNode* locate(ListNode* head, int index) {
if (index < 0) {
return nullptr;
}
ListNode* p = head->next;
int i = 0;
while (p != nullptr && i < index) {
p = p->next;
i++;
}
return p;
}
// 插入
void insert(ListNode* head, int index, int value) {
ListNode* pre = locate(head, index - 1);
if (pre == nullptr) {
cout << '插入位置无效' << endl;
return;
}
ListNode* newNode = new ListNode(value);
newNode->next = pre->next;
pre->next = newNode;
}
int main() {
// 创建带头结点的单链表
ListNode* head = new ListNode(0);
ListNode* p1 = new ListNode(1);
ListNode* p2 = new ListNode(2);
ListNode* p3 = new ListNode(3);
head->next = p1;
p1->next = p2;
p2->next = p3;
// 测试求表长
int length = getLength(head);
cout << '表长为:' << length << endl;
// 测试定位
ListNode* node = locate(head, 2);
if (node != nullptr) {
cout << '定位成功,值为:' << node->val << endl;
} else {
cout << '定位失败' << endl;
}
// 测试插入
insert(head, 1, 99);
ListNode* p = head->next;
while (p != nullptr) {
cout << p->val << ' ';
p = p->next;
}
cout << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/o7iH 著作权归作者所有。请勿转载和采集!