记录一下这一阶段所学
一、链表的定义
1.链表本质上是一个结构体变量共有两部分:第一部分是储存数据,第二部分是用于储存下一个链表的地址的指针。
2.该代码是对链表最基础的定义
struct Node{
int data;
struct Node* next
};
2链表有一个表头不储存数据只储存下一个节点的地址的指针。
二、创建链表
1.创建链表首先得创建一个表头:
struct Node* creatlist()
{
struct Node*headnode=malloc(sizeof(struct Node));
headnode->next=NULL;
return headnode;
}
通过这个表头作为牵引的火车头
2.接下来封装一个创建节点的功能
struct Node* creatnode(int data)
{
struct Node* newnode=malloc(sizeof(struct Node));
newnode->data=data;
newnode->next=NULL;
return newnode;
}
这个功能用于创建新的节点在接下来的插入节点的功能中会用到
三、插入节点(头插法)
在表头的后面插入一个新的节点只需要让表头中的指针指向新插入的节点同时新插入的节点指向原先表头指向的节点就可以完成了
void insertnode(struct Node* headnode,int data)
{
struct Node* newnode=creatnode(data);
newnode->next=headnode->next;
headnode->next=newnode;
}
这里通过上面提到的创建节点的方法创建了一个新的节点并且将该节点插入到表头的后面
四、删除节点
删除特定位置的节点的方法其实就是找到指定节点将指定节点的上一个节点指向指定节点指向的节点即可
void deletenode(struct Node* headnode,int posdata)
{
struct Node* posnode=headnode->next;
struct Node* posnodefront=headnode;
if(posnode==NULL)
{
printf("can not find the node");
}
else
{
while(posnode->data!=posdata)
{
posnodefront=posnode;
posnode=posnodefront->next;
if(posnode==NULL)
{
printf("can not find the node");
return 0;
}
}
posnodefront->next=posnode->next;
free(posnode);
}
}
这里需要对结构体指针进行判断防止posnode指向空指针而报错
五、遍历节点(打印链表)
只需定义一个指针用于遍历整个链表中的所有节点即可
void printnode(struct Node* headnode)
{
struct Node* pmove=headnode->next;
while(pmove)
{
printf("%d",pmove->data);
pmove=pmove->next;
}
printf("\n");
}
这里需要注意的是pmove指针通过移动来遍历所有节点
最后附上完整的代码
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next
};
struct Node* creatlist()
{
struct Node*headnode=malloc(sizeof(struct Node));
headnode->next=NULL;
return headnode;
}
struct Node* creatnode(int data)
{
struct Node* newnode=malloc(sizeof(struct Node));
newnode->data=data;
newnode->next=NULL;
return newnode;
}
void printnode(struct Node* headnode)
{
struct Node* pmove=headnode->next;
while(pmove)
{
printf("%d",pmove->data);
pmove=pmove->next;
}
printf("\n");
}
void insertnode(struct Node* headnode,int data)
{
struct Node* newnode=creatnode(data);
newnode->next=headnode->next;
headnode->next=newnode;
}
void deletenode(struct Node* headnode,int posdata)
{
struct Node* posnode=headnode->next;
struct Node* posnodefront=headnode;
if(posnode==NULL)
{
printf("can not find the node");
}
else
{
while(posnode->data!=posdata)
{
posnodefront=posnode;
posnode=posnodefront->next;
if(posnode==NULL)
{
printf("can not find the node");
return 0;
}
}
posnodefront->next=posnode->next;
free(posnode);
}
}
int main()
{
struct Node* list=creatlist();
insertnode(list,1);
insertnode(list,2);
insertnode(list,3);
printnode(list);
deletenode(list,2);
printnode(list);
system("pause");
return 0;
}
注:以上只是我这一阶段对单链表数据结构的理解,如有问题请向我指正,以此来提高我蒟蒻的理解能力。