动态链表的操作(增删改查)
链表一般是带头结点的链表,头结点并没有数据;
遍历链表时,先令p = head - > next,,只要p非空,就可以一直循环;
删除链表元素时,需要两个指针,一个指向将要删除的元素,另一个指向删除元素的前驱;
增加元素时,要先找到目标元素,然后新建一个节点,在这个目标元素的后面加上新建节点
#include <iostream>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<map>
using namespace std;
struct node {
int val;
node* next;
};
node* creat(int a[]){
node *head , *pre;
head = new node;
head->next = NULL;
pre = head;
for(int i = 0; i < 5; i ++){
node *temp = new node;
temp->val = a[i];
temp->next = NULL;
pre->next = temp;
pre = temp;
}
return head;
}
int findEle(node* head, int k){
node* p = head->next;
int cnt = 0;
while(p != NULL){
if(p->val == k) cnt++;
p = p->next;
}
return cnt;
}
void show(node* head){
head = head->next;
while(head){
printf("%d", head->val);
head = head->next;
}
printf("\n");
}
void deleteEle(node* head, int val){
node *p, *pre;
p = head->next;
pre = head;
while(p != NULL){
if(p->val == val){
pre->next = p->next;
delete(p);
p = pre->next;
}
else{
p = p->next;
pre = pre->next;
}
}
show(head);
}
int main()
{
int a[5] = {1, 4, 3, 4, 5};
node* head = creat(a);
show(head);
int ans = findEle(head, 4);
printf("%d\n", ans);
deleteEle(head, 4);
system("pause");
return 0;
}
静态链表
静态链表的思想是哈希,将元素的地址直接与数组下标向对应,查找较为方便,但只适用于地址较小的题目
静态链表常见步骤:
1.储存所有节点,为所有节点设置初始flag属性;
2.遍历整个链表,记录有效元素,如果想省空间,可以直接修改flag属性,代表此元素在链表上;也可以拿一个数组存储有效元素;
3.对有效元素进行排序