#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
struct LinkNode {
int data;
struct LinkNode* next;
};
void printList(struct LinkNode* li) {
if (li == NULL) { return; }
while (li->next!=NULL) {
li = li->next;
printf("%d ", li->data);
}
printf("\n");
}
struct LinkNode* newDynamicList(){
struct LinkNode* head = (struct LinkNode*)malloc(sizeof(struct LinkNode));
struct LinkNode* temp = head;
int num = 0;
while (1) {
printf("输入节点:");
scanf("%d", &num);
if (num == -1) {
break;
}
struct LinkNode* newNode = (struct LinkNode*)malloc(sizeof(struct LinkNode));
newNode->next = NULL;
newNode->data = num;
temp->next = newNode;
temp = temp->next;
}
return head;
}
void deleteDynamicList(struct LinkNode* li) {
if (li == NULL) { return; }
struct LinkNode* temp = li->next;
while (temp!=NULL) {
struct LinkNode* next = temp->next;
printf("free :%d", temp->data);
free(temp);
temp = next;
}
li->next = NULL;
}
void insertList(struct LinkNode* li,int posData,int newData) {
if (li == NULL) { return; }
struct LinkNode* previous = li;
struct LinkNode* temp = li->next;
while (temp != NULL) {
if (temp->data == posData) {
break;
}
previous = temp;
temp = temp->next;
}
struct LinkNode* newNode = (struct LinkNode*)malloc(sizeof(struct LinkNode));
newNode->data = newData;
previous->next = newNode;
newNode->next = temp;
}
void deleteList(struct LinkNode* li, int posData)
{
struct LinkNode* previous = li;
struct LinkNode* temp = li->next;
while (temp!=NULL) {
if (temp->data == posData) {
struct LinkNode* t = temp;
previous->next = temp->next;
temp = previous->next;
free(t);
t = NULL;
}
else {
previous = temp;
temp = temp->next;
}
}
}
int main(int argc, char* argv[])
{
printf("创建链表\n");
//创建链表
struct LinkNode* head = newDynamicList();
//打印链表
printList(head);
//插入节点
insertList(head, 20, 1000);
insertList(head, 30, 2000);
insertList(head, 90, 9000);
//打印链表
printList(head);
//删除指定节点
deleteList(head,20);
deleteList(head,30);
deleteList(head, 40);
deleteList(head, 50);
//打印链表
printList(head);
//删除链表
deleteDynamicList(head);
system("pause");
return EXIT_SUCCESS;
}