#include<stdio.h>
#include<stdlib.h>
struct test
{
int data;
struct test* next;
};
void printLink(struct test* head)
{
struct test* point;
point = head;
while (point != NULL)
{
printf("%d ", point->data);
point = point->next;
}
}
void GetNum(struct test* head)
{
int n = 0;
struct test* point = head;
while (point != 0)
{
point = point->next;
n++;
}
printf("%d\n", n);
}
int Search(struct test* head, int data1)
{
while (head != NULL)
{
if (head->data == data1)
{
return 1;
}
else
{
return 0;
}
head = head->next;
}
}
int insertafterbehind(struct test* head, int data, struct test* new)
{
struct test* p = head;
while (p!= NULL)
{
if (p->data == data)
{
new->next = p->next;
p->next = new;
return 1;
}
p = p->next;
}
return 0;
}
struct test* insertafterfor(struct test* head, int data, struct test* new)
{
struct test* p = head;
if (p->data == data)
{
new->next = head;
return new;
}
while (p->next != NULL)
{
printf("data:%d,point:%d\n", p->next->data, data);
if (p->next->data == data)
{
new->next = p->next;
p->next = new;
printf("插入成功");
return head;
}
p = p->next;
}
printf("链表里没有这个数:%d\n", data);
return head;
}
struct test* deletNode(struct test* head, int data)
{
struct test* p = head;
if (p->data == data)
{
head = head -> next;
free(p);//此处静态常量&t1传过来的地址不能free,所以在main里定义了一个变量指针p.
return head;
}
while (p->next != NULL)
{
if (p->next->data == data)
{
p->next = p->next->next;
return head;
}
p = p->next;
}
return head;
}
int main()
{
int i = 0;
int a[3] = { 1,2,3 };
for (i; i < sizeof(a) / sizeof(int); i++)
{
printf("数组打印:%d \n", a[i]);
}
struct test t1 = { 1,NULL };
struct test t2 = { 2,NULL };
struct test t3 = { 3,NULL };
struct test t4 = { 4,NULL };
struct test t5 = { 5,NULL };
struct test* p = (struct test*)malloc(sizeof(struct test *));
p->data = 1;
p->next = &t2;
//t1.next = &t2;
t2.next = &t3;
t3.next = &t4;
t4.next = &t5;
struct test* head = NULL;
head = p;
struct test new = { 666,NULL };
struct test new1 = { 888,NULL };
puts("打印插入前的链表:");
printLink(head);
putchar('\n');
puts("打印从后面插入的链表:");
insertafterbehind(head,5,&new);
printLink(head);
putchar('\n');
puts("打印从前面插入的链表:");
head = insertafterfor(head, 3, &new1);
printLink(head);
putchar('\n');
puts("打印删除后的链表:");
head = deletNode(head, 2);
printLink(head);
/*putchar('\n');
printf("%d %d %d\n",t1.data,t2.data,t3.data);
putchar('\n');
GetNum(&t1);
putchar('\n');
puts("请输入你要查找的数字: ");
int ret = Search(&t1,6);
if(ret ==1)
{
puts("have 1");
}
else
{
printf("no 1\n");
}*/
//system("pause");
return 0;
}