#include <stdio.h>
#include <stdlib.h>
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;
}
//创建节点
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 deleteNode(struct Node *headNode, int posData) {
//查找法
struct Node *posNode = headNode->next;
struct Node *posNodeFront = headNode;
if (posNode = NULL) {
printf("无法删除链表为空");
} else {
while (posNode->data != posData) {
posNodeFront = posNode;
posNode = posNodeFront->next;
if (posNode == NULL) {
printf("没有相关信息,无法删除\n");
return;
}
}
posNodeFront->next = posNode->next ;
free(posNode);
}
}
int main() {
struct Node *list = createList(); //创建链表
insertNodeByHead(list, 1);
insertNodeByHead(list, 2);
insertNodeByHead(list, 3);
printList(list);
deleteNode(list, 2);
printList(list);
system("pause");
return 0;
}