链表中由数据域和指针域
- 头结点的指针域为null就说明链表为空
- 头指针会指向头结点或首元结点。
Tyepdef struct student{
int score;//数据域
struct student *next;//指针域
}LinkList;
LinkList *a; //声明
#include#include struct Node{ int data; struct Node* next; }; 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; }
- 初始了三个空链表
- 创建一个静态链表
动态内存申请+模块化设计
- 创建链表(创建一个表头表示整个链表)
- 创建结点
- 插入结点
- 删除结点
- 打印遍历链表
- 打印结点(遍历)
-
头插法
-
插入前
-
插入时
-
-
删除(指定位置删除)
#include增加 删除#include struct Node{ int data; //数据域 struct Node* next; //指针域 }; struct Node* createList(){ struct Node* headNode = (struct Node*)malloc(sizeof(struct Node)); //headNode 成为了结构体 //变量使用前必须初始化 //headNode->data=1; headNode->next = Null; return headNode; } //创建结点 struct Node* createNode(int data){ struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)) newNode->data = data; newNode->next = null; return newNode; } //遍历(查) void printList(struct Node* headNode){ struct Node* pMove = headNode->next; while(pMove){ printf("%d",pMove->data); pMove = pMove->next; } printf("n"); } //头插入(参数:插入哪个链表,插入结点的数据是多少) void insertNodeByHead(struct Node* headNode,int data){ //1.创建插入的结点 struct Node* newNode = createNode(data) newNode->next = headNode->next; headNode->next = newNode; } //尾插法 void insertNodeInEnd(struct Node *EndNode, int data) { //没有第一个元素 就直接把list的next指向新节点 if (list->next == NULL) { list->next = creatNode(data); return; } //每次操作必须使用代理指针!! struct Node *p = list->next; while (p->next) {//不能判断p 因为要知道上一个有效节点 p = p->next; } p->next = creatNode(data);//不应该是p=creatNode() 要知道上一个节点 并指向其 } //删除(参数:删除哪个结点headNode ,指定位置(数据)) void deleteNodeByAppion(struct Node* headNode,int posData){ struct Node* posNode = headNode->next; //(只能从表头的下一个查找) struct Node* posNodeFront = headNode; if(posNode==NULL){ printf('无法删除,链表为null') }else{ while(posNode->data != posData){ posNodeFront = posNode; posNode = posNodeFront->next; if(posNode == NULL){ ptintf("没有找到相关信息,无法删除"); return; } } posNodeFront->next=posNode->next; free(posNode); //删除结点 } } int main(){ system("pause"); return 0; }
链表增删元素更方便



