#include <bits/stdc++.h>
using namespace std;
//链表的一些操作
//1.链表的概念
struct node {
int data;
node *next;
};
// 2.链表的分配空间 及其释放
//c语言需要用malloc函数 头文件 stdlib.h
int *p = (int *)malloc (sizeof (int));
//需要释放内存
free(p);//p本身没有消失,但是他指向了空地址
// 3.创建链表
node * creat(int Arrar[])//将数组里的元素转为链表当中数据
{
node *p,*pre,*head;//pre保存当前结点前驱
head = (node*)malloc(sizeof(node))
head -> next = NULL;
pre = head;
for (int i = 0;i<10;i++)
{
p = (node*)malloc(sizeof(node));//新建结点 开辟新空间
p->data = Arrar[i];
p->next=NULL;
pre ->next = p;//前驱结点的指针域指向当前地址
pre = p;//把pre设置为p 作为下一个结点的前驱结点
}
return head;//返回头节点指针
}
//4.查找元素
int search(node*head,int x)//查找x并且返回x的个数
{
int count = 0;
node* p = head->next;//从第一个结点开始
while(p)//其实也相当于遍历链表了
{
if (p->data==x) count++;
p = p->next;
}
return count;
}
// 5.插入元素
void insert(node*head,int pos,int x)//将x插入到以head为头节点,位置为pos的地方
{
node*p=head;
for (int i = 1;i<pos;i++)
{
p=p->next;//找到要插入位置的前一个结点
}
node *q = (node*)malloc(sizeof (node));
q->data = x;//新结点数据域
q->next = p->next;//新节点的next应该就是p的下一个
p->next = q; //前一个位置的结点指向新节点
}
//6.删除元素
void delte(node*head,int x)//删除数据域为x的结点
{
node *p = head;
node *pre = head;
whlile (p!=NULL)
{
if (p->data == x)//执行删除操作 当前结点需要删除
{
//需要上一个结点来操作
pre -> next = p->next;//相当于把p这个结点给忽略了
free(p);
p = pre->next;//下一次需要检测的点自动改为下一个结点
}
else{
pre = p;//是需要检测的点的上一个结点
p = p->next;//这个是下一次需要检验的结点
}
}
}
int main()
{
return 0;
}
地址这个东西吧,其实很奇妙,就算命名不一样,但是只要表示一块相同的空间,里面的内容都会一样的,如果想要自己一块这样独立的空间,就需要申请,同时,如果不用了,就需要释放,free掉。而链表的几个操作,无非就是地址的指向改变罢了,需要搞清楚pre,p的实际运用,可以画个图去理解一下。