#include<stdio.h>#include<stdlib.h>//1.Declarative node structurestruct node{int data;struct node *next;};//5.DeclarativevoidprintfLinkList(struct node *head);voidinsertLinkList(struct node *head,int location,int value);voiddeleteLinkList(struct node *head,int location);voidupdateLinkList(struct node *head,int oldValue,int newValue);voidmain(){//2.initializationint num[]={20,21,3,19,19,45};int length =sizeof(num)/sizeof(num[0]);struct node *head =NULL,*tail =NULL,*newNode =NULL;
head =(struct node*)malloc(sizeof(struct node*));
head->data=0;
tail=head;//3.Connect the new node to the linked listfor(int i =0; i<length;i++){
newNode =(struct node*)malloc(sizeof(struct node*));
newNode->data=num[i];
newNode->next=NULL;
tail->next=newNode;
tail=tail->next;}
head->data=length;//4.1 queryprintf("query:\n");printfLinkList(head);//4.2 insertint location =0,value =88;insertLinkList(head,location,value);printfLinkList(head);//4.3 delete
location =1;deleteLinkList(head,location);printfLinkList(head);//4.4 updateint oldValue =21;int newValue =88;updateLinkList(head,oldValue,newValue);printfLinkList(head);}//6.definitionvoidprintfLinkList(struct node *head){struct node * tail;
tail=head->next;while(tail!=NULL){printf("%4d",tail->data);
tail=tail->next;};printf("\n");}voidinsertLinkList(struct node *head,int location,int value){printf("insert:\n");struct node*tail;
tail = head;int i =0;//1.find the location of you want to insertwhile(i<location){
tail=tail->next;
i++;}//2.creates a new node to insertstruct node * newNode =NULL;
newNode =(struct node *)malloc(sizeof(struct node*));
newNode->data = value;
newNode->next =NULL;//3.connects the back of tail to become the new node's next
newNode->next = tail->next;//4.connects the new node to the back of tail
tail->next = newNode;(head->data)++;}voiddeleteLinkList(struct node *head,int location){printf("delete:\n");struct node *tail;
tail = head;int i =0;//1.find the location before the node you want to deletewhile(i<location){
tail=tail->next;
i++;}//2.creates a new node to save the location of deletestruct node *delNode;//3.replace the delete location after the tail to be delNode
delNode = tail->next;//4.connects tail and the location of after delNode
tail->next = delNode->next;//5.free the space of delNodefree(delNode);(head->data)--;}voidupdateLinkList(struct node *head,int oldValue,int newValue){printf("update\n");struct node *tail;
bool flag = false;
tail = head;//1.Determine if the value exists find itwhile(true){//2.if it dosen't exist exitif(tail->next==NULL)break;//3.if find it change the flag to be true and exitif(tail->data==oldValue){
flag = true;break;}
tail=tail->next;}//4.if the flag is false print error message otherwise replace the oldValue to newValueif(flag == false){printf("the %d is not exist",oldValue);}else{
tail->data=newValue;}}