// #include "iostream"
// using namespace std;
#include <stdlib.h>
#include <time.h>
#include <iomanip.h>
#include <iostream.h>
#define MAX 50
typedef struct Node *link,Node;
//双链表的操作
struct Node
{
link prev;
link next;
int value;
int index;
};
int AddNode(Node *node);
int DelNode(int value);
Node* NewNode();
void PrintNode(int order);//order =0 正序 order = 1倒序
Node *head;
int main()
{
head = NewNode();
if (head ==NULL)
{
return -1;
}
for(int i =0; i< MAX ;i++)
{
Node *p = NewNode();
p->value = rand();
p->index = i +1;
AddNode(p);
}
PrintNode(0);
DelNode(292);
PrintNode(1);
return 0;
}
int AddNode(Node *node)
{
if (head == NULL)
{
return -1;
}
Node* cur = head;
Node* prev = cur;
while (cur->next != NULL)
{
if (cur->value <= node->value)
{
prev = cur;
cur = cur->next;
}
else
{
prev ->next = node;
node->prev = prev;
node->next = cur;
cur->prev = node;
break;
}
if (cur == head)
{
prev ->next = node;
node->prev = prev;
node->next = cur;
cur->prev = node;
break;
}
}
if (cur->next == NULL)
{
prev->next = node;
node->next = cur;
node->prev = prev;
cur->prev = node;
}
return 0;
}
int DelNode(int value)
{
Node *ptr = head->next;
Node *prev = ptr;
while (ptr->next!= head->next)
{
if (ptr->value == value)
{
Node* temp = ptr;
prev->next = ptr->next;
ptr->next->prev = prev;
free (temp);
cout<<"Delete Node:"<<value<<endl;
break;
}
else if (ptr->value < value)
{
prev = ptr;
ptr= ptr->next;
}
else
{
cout<<"None"<<endl;
break;
}
}
return 0;
}
Node* NewNode()
{
Node *ptr =(Node*)malloc(sizeof(Node));
if (!ptr)
{
cout<<"Allocate Failure"<<endl;
return NULL;
}
else
{
ptr->value = -1;
ptr->index = -1;
ptr->next =ptr->prev = NULL;
return ptr;
}
}
void PrintNode(int order)
{
Node *ptr;
int i=1;
if (!order)
{
ptr = head->next;
cout<<"up order"<<endl;
while (ptr->next!= head->next)
{
cout<<i++<<":"<<ptr->value<<endl;
ptr = ptr->next;
}
}
else
{
ptr = head->prev;
cout<<"down order"<<endl;
while (ptr->prev!= head->prev)
{
cout<<i++<<":"<<ptr->value<<endl;
ptr = ptr->prev;
}
}
return ;
}