数据结构 -- 单链表创建之头插法和尾插法

头插法:需要保证每次插入的新节点,都是链表的首节点。

尾插法:需要保证每次插入的新节点,都是链表的最后一个节点,且其指向的下一个节点为NULL

以下代码在 vs2010 上测试通过:

#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>

#define TRUE 1
#define FALSE 0 

typedef struct NODE{
	int value;
	struct NODE *next;
}Node;

//int link_create_tail(Node *link,int length);
int link_create_head(Node *list,int length);
int main(){
	Node *link = NULL;
	int length,result,cresult;
	printf("请输入链表的长度:\n");
	result = scanf("%d",&length);
	if(result == 0){
		return FALSE;
	}
	//cresult = link_create_tail(link,length);
	cresult = link_create_head (link,length);
	if(cresult == 1){
		printf("长度为 %d 的链表创建成功\n",length);
	}
	system("pause");
	return TRUE;
}
//单链表创建-》头插法
int link_create_head(Node *list,int length){
	Node *new_node;

	int i,number ,res;
	list = (Node *)malloc(sizeof(Node));
	list->next = NULL ;
	if(list== NULL){
		return FALSE;
	}
	for(i=0; i<length; i++){
		printf("请输入数字:\n");
		res = scanf("%d",&number);
		if(res == NULL){
			return FALSE;
		}
		new_node = (Node *)malloc(sizeof(Node));
		new_node->value = number ;
		new_node->next = list->next ;
		list->next = new_node;	
	}
	return  TRUE ;
}
/*
//单链表创建-》尾插法
int link_create_tail(Node *list,int length){
	Node *p;
	Node *new_node;
	int i,number,res;
	list = (Node *)malloc(sizeof(Node));
	p = list;
	for(i = 0 ; i < length ; i++){
		new_node = (Node *)malloc(sizeof(Node));
		if(new_node == NULL){
			return FALSE;
		}
		
		printf("请输入链表的值:\n");
		res = scanf("%d",&number);
		if(res == 0){
			return FALSE;
		}
		
		new_node->value = number;
		p->next = new_node;
		p = new_node;	
	}
	p->next = NULL;
	return TRUE;

}
*/

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值