#include<stdio.h>
#include<stdlib.h>
struct Node{
int value;
struct Node *next;
};
void insertNode(struct Node **head,int value){
struct Node *pre;
struct Node *cur;
struct Node *new;
cur = *head;
pre = NULL;
while(cur!=NULL&&cur->value<value){
pre = cur;
cur = cur->next;
}
new = (struct Node *)malloc(sizeof(struct Node));
if(new==NULL){
printf("内存分配失败!\n");
exit(1);
}
new->value=value;
new->next=cur;
if(pre==NULL){
*head = new;
}
else{
pre->next=new;
}
}
void deleteNode(struct Node **head,int value){
struct Node *pre;
struct Node *cur;
cur=*head;
pre=NULL;
while(cur!=NULL&&cur->value!=value){
pre=cur;
cur=cur->next;
}
if(cur==NULL){
printf("找不到匹配的节点\n");
return;
}
else{
if(pre==NULL){
*head=cur->next;
}
else{
pre->next=cur->next;
}
free(cur);
}
}
void printNode(struct Node *head){
struct Node *cur;
cur=head;
while(cur!=NULL){
printf("%d ",cur->value);
cur=cur->next;
}
putchar('\n');
}
int main(){
struct Node *head=NULL;
int input;
printf("开始测试插入整数...\n");
while(1){
printf("请输入一个整数(-1表示结束):");
scanf("%d",&input);
if(input==-1){
break;
}
else{
insertNode(&head,input);
printNode(head);
}
}
printf("开始测试删除整数...\n");
while(1){
printf("请输入一个整数(-1表示结束):");
scanf("%d",&input);
if(input==-1){
break;
}
else{
deleteNode(&head,input);
printNode(head);
}
}
return 0;
}
评论0