E:\arithmetic\Link
#include <stdio.h>
#include <stdlib.h>//molloc free
struct LinkNode;
void printLink(struct LinkNode *head);
void addToLink(struct LinkNode **head, int value);
void deleteLink(struct LinkNode **head, int value);
int main(int argc, char *argv[])
{
//测试用例 a,添加删除正常值;b,传入链表为NULL;c,删除头结点,删除未节点,删除中间节点,删除不存在的节点
int a[] = {1,2,3,4,5,6,7,8,9,0};
struct LinkNode *link1 = NULL;
int i;
for(i=0 ; i<10 ; i++){
addToLink(&link1, a[i]);
}
printLink(link1);
deleteLink(&link1, 1);
printLink(link1);
deleteLink(&link1, 0);
printLink(link1);
deleteLink(&link1, 12);
printLink(link1);
deleteLink(&link1, 4);
printLink(link1);
deleteLink(NULL, 4);
return 0;
}
struct LinkNode {
int value;
struct LinkNode *next;
};
void printLink(struct LinkNode *head){
if(head == NULL){
printf("this link is NULL, quit!\n");
return;
}
while(head != NULL){
printf("%d\t", head->value);
head = head->next;
}
printf("\n");
}
void addToLink(struct LinkNode **head, int value){
struct LinkNode *t = malloc(sizeof(struct LinkNode));
if(t == NULL){
printf("malloc failed!\n");
return;
}
t->value = value; //!!
t->next = NULL; //!!
if(head == NULL){//!!
printf("&head is NULL\n");
return;
}
if(*head == NULL){//!!
*head = t;//!!
return;
}
struct LinkNode *h = *head;
while(h->next != NULL)
h = h->next;
h->next = t;
}
void deleteLink(struct LinkNode **head, int value){
if(head == NULL){
printf("&link is NULL , quit!\n");
return;
}
if(*head == NULL){
printf("link is NULL, quit!\n");
return;
}
struct LinkNode *t = *head;
if(t->value == value){
*head = t->next;
}
else{
struct LinkNode *t2 = NULL;
while(t->value != value){
t2 = t;
t = t->next;
if(t == NULL){
printf("failed to find in link!\n");
return;
}
}
t2->next = t->next;
}
free(t);
}