简单来说:
头插法:将每次新的结点插在最前面
尾插法:将每次新的结点插在最后面
注意:设一个空的头结点,不含data
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}node;
node* BuildList1(int num)//头插法
{//建造一个空的头结点
node* head = (node* )malloc(sizeof(node));
head->next = NULL;
for(int i=0; i<num; i++){
node* p = (node* )malloc(sizeof(node));
p->data = rand()%10;
p->next = head->next;
head->next = p;
}
return head;
}
node* BuildList2(int num)//尾插法
{
node* head = (node* )malloc(sizeof(node));
node* p1 = head;
for(int i=0; i<num; i++){
node* p2 = (node* )malloc(sizeof(node));
p2->data = rand()%10;
p2->next = NULL;
p1->next = p2;
p1 = p2;
}
return head;
}
int main()
{
node* p1, *p2;
int num;
printf("Enter the number of linked list nodes:\n");
scanf("%d",&num);
printf("头插法 :\n");
p1 = BuildList1(num);
for(int i=0; i<num; i++){
printf("%d\t", p1->next->data);
p1 = p1->next;
}
printf("\n尾插法 :\n");
p2 = BuildList2(num);
for(int i=0; i<num; i++){
printf("%d\t", p2->next->data);
p2 = p2->next;
}
}