/* 动态创建一个链表:动态内存申请+模块化设计 1、创建链表 headNode指针 2、创建结点 3、插入节点 4、删除节点 5、打印遍历链表(测试) */ #include <stdio.h> #include <stdlib.h> struct Node{ int data; //数据域 struct Node* next; //指针域 }N; struct Node* creatList(){ struct Node* headNode = (struct Node*)malloc(sizeof(struct Node)); //headNode变成了结构体变量 headNode->next = NULL; return headNode;//返回头节点地址 }//创造链表 struct Node* createNode(int data){ struct Node* Node = (struct Node*)malloc(sizeof(struct Node)); Node->data=data; Node->next=NULL; return Node;//返回结点地址 } //创造节点 void printList(struct Node* headNode){ struct Node* pMove=headNode->next; while(pMove){ printf("%d\t",pMove->data); pMove=pMove->next; } printf("\n"); } //打印链表 void insertNodeByHead(struct Node* headNode,int data){ struct Node* NewNode = createNode(data); NewNode->data = data; NewNode->next = headNode->next; headNode->next = NewNode; } //头插法 void deleteNodeByAppoint(struct Node* headNode,int data){ struct Node* posNode = headNode->next; struct Node* posNodeFront = headNode; if(posNode == NULL) printf("表空,任务失败"); else{ while(posNode->data != data){ posNodeFront = posNode; posNode = posNode->next; if(posNode == NULL){ printf("表尽,任务失败"); return; }//if }//while posNodeFront->next=posNode->next; free(posNode); } } //删除指定结点 int main(){ struct Node* list=creatList(); insertNodeByHead(list,1); insertNodeByHead(list,2); insertNodeByHead(list,3); printList(list); deleteNodeByAppoint(list,2); printList(list); system("pause"); return 0; }