(1)单个节点创建非常方便,普通的线性内存通常在创建的时候就需要设定数据的大小
(2)节点的删除非常方便,不需要像线性结构那样移动剩下的数据
(3)节点的访问方便,可以通过循环或者递归的方法访问到任意数据,但是平均的访问效率低于线性表
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define MAXSIZE 50
typedef struct node
{
int value;
struct node *next;
}node;
node *head = NULL;
int g_size = 0;
node* createNode(int value)
{
node* p = (node*)malloc(sizeof(node));
if (p == NULL) {
perror("this is no space in Line_18.\n");
exit(0);
}
p->value = value;
p->next = NULL;
}
bool isEmpty()
{
return g_size == 0;
}
bool isFull()
{
return g_size == MAXSIZE;
}
bool headInsert(node *p)
{
if (isEmpty())
{
head = p;
g_size++;
return TRUE;
}
if (isFull())return FALSE;
p->next = head;
head = p;
g_size++;
return TRUE;
}
bool tailInsert(node*p)
{
node*pre = head;
if (isEmpty())
{
head = p;
g_size++;
return TRUE;
}
if (isFull())return FALSE;
while (pre->next != NULL)
{
pre = pre->next;
}
p = pre->next;
return TRUE;
}
bool preInsert(node*p, node*loca)
{
if (isFull())return FALSE;
if (loca == head)return headInsert(p);
node* pre = head;
while (pre->next != loca)pre = pre->next;
p = pre->next;
p->next = loca;
return TRUE;
}
bool dInsert(node*p, node*loca)
{
if (isFull())return FALSE;
if (loca->next == NULL) return tailInsert(p);
node*pd = head;
while (loca->next != pd)pd = pd->next;
p = loca->next;
p->next = pd;
return TRUE;
}
void deleteNode(node*p)
{
node *pre = head;
while (pre->next !=p)
{
pre = pre->next;
}
pre->next = p->next;
p->next = NULL;
free(p);
g_size--;
}
void deleteALl()
{
node *p = head;
node *pre;
while (p != NULL)
{
pre = p->next;
free(p);
p = pre;
}
printf("链表已经销毁了!\n");
g_size = 0;
}
void alterValue(node*p,int value)
{
p->value = value;
}
void traverse()
{
node *p = head;
while (p != NULL) {
printf("p->value = %d",p->value);
p = p->next;
}
printf("遍历完毕");
}
node*search(int value)
{
node*p = head;
while (p != NULL)
{
if (p->value == value)return p;
p = p->next;
}
return NULL;
}
int *linkToArray()
{
node*p = head;
int i = 0;
int array[g_size] = {0};
while (p != NULL)
{
array[i++] = p->value;
p = p->next;
}
return array;
}
bool arrayToLink(int *array)
{
int size = g_size;
node*p = head;
if (size != strlen(array)) return FALSE;
for (size = 0; size < g_size; size++)
{
p->value = array[size];
p = p->next;
}
return TRUE;
}
int* bubbleSort(int *array)
{
int size = strlen(array);
int i = 0;
int j = 0;
int temp = 0;
for (i = 0; i < size-1; i++)
{
for (j = i + 1; j < size; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
void sortTop()
{
int *array = bubbleSort(linkToArray());
if (!arrayToLink(array))printf("this is error in sort");
}