#pragma once
#include <iostream>
using namespace std;
struct Node {
int val;
Node* next;
Node(int val, Node* next) :val(val), next(next) {};
Node(int val) :val(val), next(nullptr) {};
};
class LinkedList {
public:
Node* create() {
Node* head = nullptr;
Node* tail = nullptr;
int k;
cout << "输入-1退出创建程序:";
cin >> k;
while (k != -1) {
Node* newnode = new Node(k);
if (head == nullptr) {
head = newnode;
tail = newnode;
}
else {
tail->next = newnode;
tail = newnode;
}
cout << "输入-1退出创建程序:";
cin >> k;
}
return head;
}
void show(Node* head) {
Node* cur = head;
while (cur != nullptr) {
cout << cur->val << "->";
cur = cur->next;
}
}
int len(Node* head) {
Node* cur = head;
int size = 0;
while (cur != nullptr) {
size++;
cur = cur->next;
}
return size;
}
Node* deleteAtIndex(Node* head,int idx) {
Node* cur = head;
if (idx == 0) { return head->next; }
else {
for (int i = 0; i < idx - 1; ++i) {
cur = cur->next;
}
Node* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
return head;
}
Node* deleteAtval(Node* head, int val) {
Node* cur = head;
if (head->val == val) { head = head->next; }
while (cur->next != nullptr) {
if (cur->next->val == val) {
Node* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
else { cur = cur->next; }
}
return head;
}
Node* addAtIndex(Node* head, int val, int idx) {
Node* newnode = new Node(val);
Node* cur = head;
if (idx == 0) {
newnode->next = cur->next;
cur->next = newnode;
return head;
}
else {
while (idx--) { cur = cur->next; }
}
newnode->next = cur->next;
cur->next = newnode;
return head;
}
};
链表不同于数组,数组中的数据是连接的,较为密集的,内存地址是连续的,比如我构建一个整数类型的数组,数组中的每个数都是整数,占4个字节,也就是32位,在查询内存地址时就会发现相邻的数字的内存地址只相差4,而链表则是通过链条的方式,将散落在各个地方的数据连接起来,较为灵活,同时方便修改
这个是写了个头文件,下面是我调用的主程序
#include <iostream>
#include"LinkedList.h";
using namespace std;
int main() {
LinkedList l;
Node* head = l.create();
head = l.addAtIndex(head, 1000, 0);
head = l.addAtIndex(head,1000, 1);
l.show(head);
}