#include <stdio.h>
#include <stdlib.h>
#include "node.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct _list{
Node* head;
}List;
void add(Node *head,int number);
void print(List *plist);
int main(int argc, char *argv[]) {
int number;
List list;
list.head=NULL;
do{
scanf("%d",number);
if(number!=-1){
add(&list,number);
}
}while(number!=-1);
print(&list); //打印链表
//在链表中搜索指定number
scanf("%d",&number);
Node *p;
int isFound=0;
for(p=list.head;p;p=p->next){
if(p->value==number){
printf("找到\n");
isFound=1;
break;
}
}
if(!isFound){
printf("没找到\n");
}
//在链表中删除指定number
Node *q;
for(q=NULL,p=list.head;p;q=p,p=p->next){
if(p->value==number){
if(q){ //考虑头结点为空的情形
q->next=p->next;
}
else{
list.head=p->next; //此时p,q均为空结点
}
free(p);
break;
}
}
//链表的释放
for(p=head;p;p=q){
q=p->next;
free(p);
}
return 0;
}
void add(List *pList,int number)
{
//add to linked-list
Node *p=(Node*)malloc(sizeof(Node));
p->value=number;
p->next=NULL;
//Find the last
Node *last=pList->head;
if(last){
while(last->next){
last=last->next;
}
//attach
last->next=p;
} else{
pList->head=p;
}
}
void print(List *plist){
Node *p;
for(p=plist->head;p;p=p->next){
printf("%d\t",p->value);
}
printf("\n");
}