数据结构:存储数据的结构
有头链式结构
有头链表
链式结构:结构体变量与结构体变量连接在一起
结构体:数据域,指针域
struct Node
{
int data;
struct Node next;
}
#include <stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Nodenext;
};
int main()(创建结构体变量)
{
struct Node node1={1,NULL};
struct Node node2={2,NULL};
struct Node node3={3,NULL};
node1.next=&node2;
node2.next=&node3;
线性结构称为链表
指针指向链表的首地址,该线性结构为链表
内存不连续,数据存在不同类型的数组
不能通过下标方式去访问
只能通过指针去访问
能够自己实现插入
有头链表
表头不存放数据去操作
表头:结构体变量
struct Node * createList()
指针 变成变量
动态内存申请
struct Node*headNode=(struct Node星号※)malloc(sizeof(struct Node));
headNode->next=NULL;
return newNode;
}
表头法插入
void insertByhead(struct Node* headNode,int data)
{
插入之前首先的创建节点
struct Node*newNode=createNode(data);
nextNode->next=headNpde->next;
headNode->next=newNode;
}
void printLidt(struct Nodeheadnode)
{有表头链表,所以从第二个节点开始打印
struct Node pMove=headNode->next;
while(pMove)
{
printf("%d–>",pMove->data);
pMove=pMove->next;
}
printf("\n");
int main()
{
struct Nodelist=createList();链表创建
insertByhead(list,1);
insertByhead(list,2);
insertByhead(list,3);
printList(list);
}
int main()
{
struct Nodelist=createList();
for(int i=0;i<10;i++)
{
insertByHead(list,i);
}
}相比于数组更简洁方便
表尾插入
找到表尾
当指针下节点为NULL则为表尾
void insertByTail(struct NodeheadNode,int data)
{
struct NodenewNode=createNode(data);
struct Node*tailNode=headNode;
while(tailNode->next!=NULL)
{
tailNode=tailNode->next;
}
tailNode->next=newNode;
}
int main()
{
insertByTail(list,-1);
printList(list);
}