#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
using namespace std;
typedef struct node{
int ele;
node* next;
}node;
bool cmp(int a, int b)
{
return a < b;
}
void create(node** start)
{
*start = (node*) malloc (sizeof(node));
(*start)->next = NULL;
}
void insert(int ele, node *head)
{
node* cur = (node*) malloc (sizeof(node));
cur->ele = ele;
node* p = head;
if(p == NULL)
{
head->next = cur;
cur->next = NULL;
return ;
}
while(p->next != NULL && cmp(ele, p->next->ele))
p = p->next;
cur->next = p->next;
p->next = cur;
}
void print(node* head)
{
node* p = head->next;
printf("head -> ");
while(p != NULL)
{
printf("[%d] -> ",p->ele);
p = p->next;
}
printf("NULL\n");
}
void dele(int ele, node* head)
{
node* p = head;
if(head->next->ele == ele)
{
node* temp = head->next;
head->next = head->next->next;
free(temp);
return ;
}
while(p->next->next != NULL && p->next->ele != ele)
p = p->next;
if(p->next->ele != ele)
printf("no such element\n");
else
{
node* temp = p->next;
p->next = p->next->next;
free(temp);
}
}
int main()
{
//freopen("ztest.txt","r",stdin);
int temp;
node* head;
create(&head);
while(scanf("%d",&temp) && temp)
{
insert(temp, head);
print(head);
}
while(scanf("%d",&temp) && temp)
dele(temp, head);
print(head);
return 0;
}
测试数据:
8 10 1 13 456 89 21 22 315 -1 -4 -849 0
456 315 -849 0