一、单链表作用:
将结构体变量和结构体变量通过结构体指针连接在一起
1)节点
节点一般情况下是由数据域和指针域结合
定义一个链表的结构类型,如下:
struct Node{
int data; //数据域
struct Node* next; //指针域(结构体指针)
};
2)存储结构
定义结构体指针,如下:
int main()
{
struct Node Node1={1,NULL};//定义结构体指针
struct Node Node2={2,NULL};
struct Node Node3={3,NULL};
return 0;
}
一般结构体指针在存储空间中互不干扰,每一个变量的下一个节点都指向NULL(空)
n个节点通过指针域相互链接形成链表,如下:
int main()
{
struct Node Node1={1,NULL};
struct Node Node2={2,NULL};
struct Node Node3={3,NULL};
Node1.next ->&Node2; //此种申请方式为静态链表,一般不使用
Node2.next ->&Node3;
return 0;
}
二、创建链表、创建节点
动态创建链表:
动态内存申请+模块化设计
创建链表(创建一个表头表示整个链表)
创建节点
插入节点
删除节点
打印/遍历链表(测试)
之前的是静态的单链表,要制作动态的单链表,需要结构体指针变量。
如何将结构体指针(节点)变成一个变量呢?
用动态内存申请malloc函数,申请一块动态内存。
创建链表list*createList();
struct Node*creatlist()
{
struct Node* headNode=(struct Node*)malloc(sizeof(struct Node));
//结构体指针(节点)变成了一个结构体指针变量
headNode->next=NULL; //变量使用前要初始化
return headNode;
};
为了插入,删除节点等操作的进行
创建节点list*creatNode(int data);
struct Node*creatNode(int date)
{
struct Node*newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->date=date;
newNode->next=NULL;
return newNode;
};
三、打印(遍历)节点、插入节点(头插法),删除节点(指定位置删除)
打印节点
从第二个节点开始打印
void printList(struct Node*headNode)
{
struct Node*Pmove=headNode->next;
while(Pmove) //当这个节点不等于NULL的时候开始打印
{
printf("%d",Pmove->date);
Pmove = Pmove->next;
}
printf("\n");
}
插入节点(头插法)
void insert_Node_By_HeadNode(struct Node*headNode/*插入哪个链表*/,int date/*插入节点的数据是多少*/)
{ //要插入的话,首先要创建插入的节点
struct Node*newNode=creatNode(date);
newNode->next = headNode->next; //newNode的下一个节点,指向neadNode的下一个
headNode->next = newNode; //headNode的下一个指向newNode
}
删除节点(指定位置删除)
void deleteNodebyAppoint(struct Node* HeadNode/*删除哪个链表中的节点*/, int data/*指定删除的数据*/)
{
struct Node* postNodeFront = HeadNode;
struct Node* postNode = HeadNode->next;
while(postNode->data != data) //判断要删除的节点中的数据
{
postNodeFront = postNode;
postNode = postNodeFront->next;
if(postNode == NULL) //走到最后一个节点
{
printf("not find data\n");
return;
}
}
postNodeFront->next = postNode->next;
free(postNode); //前面使用了malloc函数,需要手动释放,防止内存泄漏
}
四、主函数
int main()
{
/* Write C code in this online editor and run it. */
printf("Hello, World! \n");
struct Node* list = createList();
insertNodebyRear(list, 1);
insertNodebyRear(list, 2);
insertNodebyRear(list, 3);
insertNodebyRear(list, 4);
printNode(list);
deleteNodebyAppoint(list,5);
deleteNodebyAppoint(list, 3);
printNode(list);
return 0;
}