#include<stdio.h>
#include <stdlib.h>
struct test{
int data;
struct test *next;
};
/*打印数据*/
void printLink(struct test *head)
{
int count = 0;
while(head != NULL)
{
count++;
printf("NO.%d,data=%d\n",count,head->data);
head = head->next;
}
printf("total number=%d\n",count);
}
/*从前方插入*/
struct test * inserDataFromForward(struct test *head,int data,struct test *new)
{
struct test *p=head;
if(head->data == data)
{
new->next = head;
return new;
}
while(head->next != NULL)
{
if(head->next->data ==data)
{
new->next = head->next;
head->next = new;
return p;
}
head = head->next;
}
return p;
}
/*从后方插入*/
int inserDataFromBehind(struct test *head,int data,struct test *new)
{
while(head != NULL)
{
if(head->data == data)
{
new->next = head->next;
head->next = new;
}
head = head->next;
}
return 0;
}
/*删除数据*/
struct test * deleteData(struct test *head,struct test *destData)
{
struct test *p =head;
if(head->data == destData->data)
{
head = head->next;
free(p);
return head;
}
while(p->next!=NULL)
{
if(p->next->data == destData->data)
{
struct test * tmp = p->next;
p->next = p->next->next;
free(tmp);
return head;
}
p = p->next;
}
return head;
}
/*增加单个数据*/
struct test *addData(struct test* head,struct test* new)
{
if(head == NULL)
{
head = new;
}
else
{
new->next = head;
head = new;
}
return head;
}
/*尾差法创建链表*/
struct test * createLinkFromTail(struct test* head )
{
struct test *new = NULL;
struct test * p=NULL;
while(1)
{
p = head;
new = (struct test *)malloc(sizeof(struct test));
printf("please input a intger\n");
scanf("%d",&(new->data));
if(new->data == 0)
{
break;
}
if(head == NULL)
{
head =new;
new->next =NULL;
}
else
{
while(p->next !=NULL)
{
p = p->next;
}
p->next = new;
new->next =NULL;
}
}
return head;
}
/*头插法创建链表*/
struct test * createLinkFromHead(struct test* head )
{
struct test *new = NULL;
while(1)
{
new = (struct test *)malloc(sizeof(struct test));
printf("please input a intger\n");
scanf("%d",&(new->data));
if(new->data == 0)
{
break;
}
head = addData(head,new);
}
return head ;
}
int main()
{
struct test *head = NULL;
struct test New = {100,NULL};
// head = createLinkFromHead(head);
head = createLinkFromTail(head);
printLink(head);
// head = deleteData(head,&New);
// inserDataFromBehind(head,3,&New);
// head= inserDataFromForward(head,3,&New);
//printLink(head);
return 0;
}
|