C语言链表 — 头插法与尾插法

说明:头插法与尾差法的差别仅仅在于以下代码的红色部分。

头插法程序

#include "stdio.h"
#include "stdlib.h"

typedef struct node{
	int x;
	struct node *next;
}F;

int main(int argc, char* argv[])
{
	F head, *p, *p1;
	p1 = (F *)malloc( sizeof(F) );
	p1->next = NULL;
	head.next = p1;
	p1->x = 0;
	for (int i = 0; i < 5; i ++) 	{ 		
                p = (F *)malloc( sizeof(F) );
                p->next = NULL;
		p->x = i + 1;
		p->next = head.next;
		head.next = p;
	}
	for (p=head.next; p!=NULL; p=p->next)
	{
		printf("%d\n", p->x);
	}
	return 0;
}

尾插法程序

#include "stdio.h"
#include "stdlib.h"

typedef struct node{
	int x;
	struct node *next;
}F;

int main(int argc, char* argv[])
{
	F head, *p, *p1;
	p1 = (F *)malloc( sizeof(F) );
	p1->next = NULL;
	head.next = p1;
	p1->x = 0;
	for (int i = 0; i < 5; i ++) 	{ 		
                p = (F *)malloc( sizeof(F) );
                p->next = NULL;
		p->x = i + 1;
		p1->next = p;
		p1 = p1->next;
	}
	for (p=head.next; p!=NULL; p=p->next)
	{
		printf("%d\n", p->x);
	}
	return 0;
}


发表评论

邮箱地址不会被公开。