单链表专题(1)
1.什么是链表?
链表是结构体变量与结构体变量连接在一起
2.动态创建一个链表
动态内存申请+模块化设计
1.创建链表(创建一个表头表示整个链表)
2.创建结点
3.插入结点
4.删除结点
5.打印遍历链表(测试)
3.创建链表
struct Node{int data; //数据域struct Node* next; //指针域
};struct Node* createList()
{struct Node* headNode = (struct Node*)malloc(sizeof(struct Node));//headNode 成为了结构体变量headNode -> next = NULL;return headNode;
}
4.创建结点
struct Node{int data; //数据域struct Node* next; //指针域
};struct Node* createNode(int data)
{struct Node* newNode(struct Node*)malloc(sizeof(struct Node));newNode -> data = data;newNode -> next = NULL;return newNode;
}
5.打印遍历结点
void printList(struct Node* headNode)
{struct Node* pMove = headNode -> next;while(pMove){pritnf("%d", pMove -> data);pMove = pMove -> next;}
}
6.插入结点(头插法)
//插入结点,参数,插入的那个链表,插入的结点数据
void insertNodeByHead(struct Node* headNode, int data)
{//1.创建插入的结点struct Node* newNode = createNode(data);newNode -> next = headNode -> next;headNode -> next = newNode;
}
7.链表的删除(指定位置删除)
void deleteNodeByAppoin(struct Node* headNode, int posData)
{struct Node* posNode = headNode -> next;struct Node* posNodeFront = headNode;if(posNode == NULL)printf("无法删除,链表为空\n");else{while(posNode -> data != posData){posNodeFront = posNode;posNode = posNodeFront -> next;if(posNode == NULL){printf("未找到相关结点\n");return;}}posNodeFront -> next = posNode -> next;free(posNode);}
}