链表插入是在找到元素的前面插入数据,如果没有找到,就不能插入元素。
链表删除是删除找到的元素。
如果想在每一次的随机函数中,得到的数据不一样,可以使用sleep(10)函数,模拟随机数
struct node{
int data;
struct node *next;
};
typedef struct node* NODEP;
typedef struct node NODE;
void createLink(void);
void initNodeData(NODEP node);
void print(NODEP node);
void freeNode(NODEP node);
void insertNode(NODEP node);
NODEP deleteNode(NODEP node);
NODEP insertSearchNode(NODEP node,int element);
NODEP deleteSearchNode(NODEP node,int element);
#define kLen 10
static inline int dataFunction(){
srand((unsigned int)time(NULL));
int temp = rand()%12+1;
return temp;
}
void initNodeData(NODEP node){
NODEP p = node;
NODEP q = NULL;
int a[13] = {0};
for (int i = 0; i < kLen; ++i) {
int temp = rand()%12+1;
if (a[temp]) {
--i;
continue;
}
a[temp] = 1;
if (i == 0) {
p->data = temp;
p->next = q;
}
else{
q = malloc(sizeof(NODE));
q->data = temp;
q->next = p->next;
p->next = q;
p = q;
}
}
}
void createLink(void){
NODEP node = malloc(sizeof(NODE));
assert(node);
initNodeData(node);
printf("\n");
print(node);
printf("\n");
insertNode(node);
print(node);
printf("\n");
node = deleteNode(node);
print(node);
printf("\n");
}
NODEP insertSearchNode(NODEP node,int element){
assert(node);
NODEP p = node;
NODEP q = NULL;
for (;p;q = p,p = p->next) {
if (p->data == element) {
break;
}
}
return q;
}
void insertNode(NODEP node){
assert(node);
int temp = 2;//dataFunction();
printf("%d ",temp);
int data = dataFunction();
printf("%d \n",data);
NODEP p = insertSearchNode(node, temp);
if (p) {
NODEP q = malloc(sizeof(NODE));
assert(q);
q->data = data;
q->next = p->next;
p->next = q;
}
else{
printf("no search data\n");
}
}
NODEP deleteSearchNode(NODEP node,int element){
assert(node);
NODEP p = node;
NODEP q = NULL;
int flag = 0;
for (;p;q = p,p = p->next) {
if (p->data == element) {
flag = 1;
break;
}
}
if (flag) {
if (q == NULL) {
q = node;
}
}
else if (!flag){
q = NULL;
}
return q;
}
NODEP deleteNode(NODEP node){
assert(node);
int temp = dataFunction();
printf("temp:%d \n",temp);
NODEP p = deleteSearchNode(node, temp);
if (p) {
NODEP q = NULL;
if (p != node) {
q = p->next;
if (q)
{
p->next = p->next->next;
free(q);
return node;
}
else{
printf("no search data\n");
return NULL;
}
}
else {
q = p;
node = p->next;
free(q);
return node;
}
}
else{
printf("no search data\n");
return NULL;
}
}
void print(NODEP node){
NODEP p = node;
for (;p;p = p->next) {
printf("%d ",p->data);
}
printf("\n");
}
void freeNode(NODEP node){
NODEP p = node;
NODEP q = p;
for (;p;) {
printf("%d ",p->data);
p = p->next;
free(q);
q = p;
}
}