#include "iostream"
using namespace std;
#include <stdlib.h>
#include <time.h>
#define MAX 20
typedef struct Node *Link,Node;
struct Node
{
Link next;
int value;
};
Node *head; //头结点
int AddNode(Node* node);//末端插入新节点
int AddNode2(Node* node);//Head端插入新节点
int DelNode(int value);//删除节点
int PrintNodes();//打印节点
static Node* NewNode();
int main()
{
srand( (unsigned)time( NULL ) );
head = NewNode();
if (!head)
{
cout<<"head is NULL"<<endl;
}
for (int i = 0;i<MAX;i++)
{
Node *ptr = NewNode();
ptr->value = rand();
//AddNode(ptr);
AddNode2(ptr);
}
PrintNodes();
DelNode(5);
return 0;
}
static Node* NewNode()
{
Node *h = (Node*) malloc(sizeof(Node));
if(!h)
{
return NULL;
}
else
{
h->value = -1;
h->next = NULL;
return h;
}
}
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 if (cur->value > node->value)
{
prev->next = node;
node->next = cur;
break;
}
}
if (cur->next == NULL)
{
if (cur->value <= node->value)
{
cur->next = node;
}
else
{
prev->next = node;
node->next = cur;
}
}
return 0;
}
int AddNode2(Node* node) //Head端插入新节点
{
if (head == NULL)
{
return -1;
}
Node* cur = head;
Node* prev = cur;
while (cur->next != NULL)
{
if (cur->value >= node->value)
{
prev->next = node;
node->next = cur;
break;
}
else
{
prev = cur;
cur = cur->next;
}
}
if (cur->next == NULL)
{
if (cur->value <= node->value)
{
cur->next = node;
}
else
{
prev->next = node;
node->next = cur;
}
}
return 0;
}
int DelNode(int value)
{
Node* cur = head->next;
Node* prep;
Node* temp;
while (cur->next!= NULL)
{
if (cur->value < value)
{
prep = cur;
cur = cur->next;
}
else if (cur->value == value)
{
temp = cur;
prep = temp->next;
cout<<"Delete Node:"<<value<<endl;
free(cur);
break;
}
else
{
cout<<"None"<<endl;
break;
}
}
return 0;
}
int PrintNodes()
{
Node* cur = head->next;
while (cur != NULL)
{
cout<<cur->value<<endl;
cur =cur->next;
}
return 0;
}