链表的创建以及实现增删改查功能,利用了哑节点把头节点“大众化”
//创建结构体
struct Node {
int val;
Node* next;
Node(int val) {
this->val = val;
this->next = nullptr;
}
};
//全局变量
Node* head;
Node* tail;
Node* dummyhead;
//用数组传参创建链表
Node* createList(vector<int>&a) {
for (int i = 0; i < a.size(); i++) {
Node *newnode = new Node(a[i]);
if (!head) {
head = newnode;
tail = newnode;
}
else {
tail->next = newnode;
tail = newnode;
}
}
return head;
}
//打印
void print(Node* head) {
while (head) {
cout << head->val<<" ";
head = head->next;
}
printf("\n");
return;
}
//增加:在index个节点前加节点val(index从0计数)
Node* add(int val,int index) {
if (!head) return head;
dummyhead = new Node(-1);
Node* newnode = new Node(val);
dummyhead->next = head;
Node* cur = dummyhead;
while (index) {
cur = cur->next;
index--;
}
newnode->next = cur->next;
cur->next = newnode;
return dummyhead->next;
}
//删除值为val的所有节点
Node* deleteNode(int val) {
if (!head) return head;
dummyhead = new Node(-1);
dummyhead->next = head;
Node* cur = dummyhead;
while (cur->next) {
if (cur->next->val==val) {
cur->next = cur->next->next;
}
else {
cur = cur->next;
}
}
return dummyhead->next;
}
//改:将节点nums1改为nums2
Node* changeNode(int nums1, int nums2) {
if (!head) return head;
Node* p = head;
while (p) {
if (p->val == nums1) {
p->val = nums2;
}
p = p->next;
}
return head;
}
//查找
bool get(int target) {
if (!head) return head;
dummyhead = new Node(-1);
dummyhead->next = head;
while (head) {
if (head->val == target) {
return 1;
}
head = head->next;
}
return 0;
}
手撕链表~~
最新推荐文章于 2023-11-18 11:21:28 发布