在链表后加入节点。
#include<stdio.h>
struct Test
{
int data;
struct Test *next;
};
int insertFromBehind(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;
}
void printLink(struct Test* head)
{
struct Test* point=head;
while(point!=NULL){
printf("%d ",point->data);
point=point->next;
}
}
int getNum(struct Test* head)
{
int num=0;
struct Test *p=head;
while(p!=NULL){
num++;
p=p->next;
}
return num;
}
int searchNum(struct Test* point,int data)
{
while(point!=NULL){
if(point->data==data){
return 1;
}
point=point->next;
}
return 0;
}
int main()
{
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};
t1.next=&t2;
t2.next=&t3;
t3.next=&t4;
t4.next=&t5;
struct Test new={100,NULL};
printf("use t1 to print three nums!\n");
printLink(&t1);
putchar('\n');
puts("after insert behind:");
insertFromBehind(&t1,3,&new);
printLink(&t1);
/*putchar('\n');
int ret=getNum(&t1);
printf("链表里的个数是:%d\n",ret);
ret = searchNum(&t1,1);
if(ret==0){
printf("no 1\n");
}
else{
printf("have 1\n");
}
ret = searchNum(&t1,8);
if(ret==0){
printf("no 8\n");
}
else{
printf("have 8\n");
}*/
return 0;
}
建立一个头结点指针然后判断他是否为空,不为空时将在这个数据前后链接起来。注意这边new需要定义。
在链表后前加入一个数据
#include<stdio.h>
struct Test
{
int data;
struct Test *next;
};
struct Test* insertFromFor(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){
if(p->next->data == data){
new->next=p->next;
p->next=new;
printf("search ok!\n");
return head;
}
p=p->next;
}
printf("do not have %d\n",data);
return head;
}
void insertFromBehind(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;
}
p=p->next;
}
}
void printLink(struct Test* head)
{
struct Test* point=head;
while(point!=NULL){
printf("%d ",point->data);
point=point->next;
}
}
int getNum(struct Test* head)
{
int num=0;
struct Test *p=head;
while(p!=NULL){
num++;
p=p->next;
}
return num;
}
int searchNum(struct Test* point,int data)
{
while(point!=NULL){
if(point->data==data){
return 1;
}
point=point->next;
}
return 0;
}
int main()
{
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 *head=NULL;
t1.next=&t2;
t2.next=&t3;
t3.next=&t4;
t4.next=&t5;
head=&t1;
struct Test new={100,NULL};
printf("use t1 to print three nums!\n");
printLink(head);
putchar('\n');
puts("after insert behind:");
insertFromBehind(head,5,&new);
printLink(head);
struct Test new2={101,NULL};
putchar('\n');
head = insertFromFor(head,2,&new2);
puts("after insert forward:");
printLink(head);
return 0;
}
同理