4.代码四
尾插法:其实与头插法相差不差,在尾插法函数中insertBehind(),传过来的head尽量不变,struct Test *p;创建临时指针p = head; 同样的,也是先判断 传过来的head 是否等于 0;等于0,则 head = new; return head; 也是用while 循环判断 p->next !==NULL;不为空一直循环到为空跳出,跳出则:p->next = new; return head; 超级无敌残暴!!!
#include<stdio.h>
#include<stdlib.h>
struct Test
{int data;struct Test *next;
};void printLink(struct Test *head)
{struct Test *point;point = head;printf("output the new insert data:\n");while(point !=NULL){printf("%d ",point->data);point = point->next;}putchar('\n');
}struct Test* insertFromHead(struct Test *head,struct Test *new)
{if(head ==NULL)
{head = new;}else{new ->next = head;head = new;}return head;
}struct Test *creatLink(struct Test *head)
{struct Test *new;while(1){new = (struct Test*)malloc(sizeof(struct Test));printf("Please input your new node data:\n");scanf("%d",&(new->data));if(new->data ==0){printf("0 quit\n");free(new);return head;}head = insertFromHead(head,new);}
}struct Test *insertBehind(struct Test *head,struct Test *new)
{struct Test *p = head;if(p ==NULL){head = new;return head;}while(p->next!=NULL){p = p -> next;}p->next = new;return head;
}int main()
{struct Test *head = NULL;struct Test t1 = {1000,NULL};head = creatLink(head);printLink(head);head = insertFromHead(head,&t1);printLink(head);struct Test t2 = {2000,NULL};head = insertBehind(head,&t2);printLink(head);return 0;
}