C++ 单链表基础操作示例:创建、删除、插入、查找
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
void printList(ListNode* head) {
ListNode* curr = head;
while (curr != NULL) {
cout << curr->val << ' ';
curr = curr->next;
}
cout << endl;
}
int length(ListNode* head) {
int len = 0;
ListNode* curr = head;
while (curr != NULL) {
len++;
curr = curr->next;
}
return len;
}
ListNode* deleteFirst(ListNode* head) {
if (head == NULL) {
return NULL;
}
ListNode* newHead = head->next;
delete head;
return newHead;
}
ListNode* insertAfter(ListNode* head, int pos, int val) {
ListNode* newNode = new ListNode(val);
if (head == NULL) {
return newNode;
}
if (pos == 0) {
newNode->next = head;
return newNode;
}
ListNode* curr = head;
int count = 0;
while (curr != NULL && count < pos) {
curr = curr->next;
count++;
}
if (curr == NULL) {
return head;
}
newNode->next = curr->next;
curr->next = newNode;
return head;
}
int main() {
ListNode* head = NULL;
int num;
while (cin >> num) {
if (num == 0) {
break;
}
ListNode* newNode = new ListNode(num);
if (head == NULL) {
head = newNode;
} else {
ListNode* curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = newNode;
}
}
printList(head);
head = deleteFirst(head);
printList(head);
int len = length(head);
cout << len << endl;
head = insertAfter(head, 1, 100);
printList(head);
ListNode* curr = head;
int pos = 0;
while (curr != NULL && curr->val != 100) {
curr = curr->next;
pos++;
}
cout << pos + 1 << endl;
return 0;
}
代码说明:
- 创建单链表:
- 使用
while
循环读取输入数据,创建ListNode
节点并插入到链表中。
- 使用
- 打印链表:
printList
函数遍历链表,输出每个节点的值。
- 删除第一个元素:
deleteFirst
函数删除链表的第一个节点,并返回新的链表头指针。
- 计算链表长度:
length
函数遍历链表,计算节点数量。
- 在指定位置插入元素:
insertAfter
函数在指定位置后插入新节点,并返回新的链表头指针。
- 查找元素位置:
- 遍历链表,查找第一个值为 100 的节点,并输出其位置。
样例输入输出:
输入:
1 2 3 4 0 9
输出:
1 2 3 4 0 9
2 3 4 0 9
5
2 100 3 4 0 9
2
原文地址: https://www.cveoy.top/t/topic/o8Dz 著作权归作者所有。请勿转载和采集!