数据结构 -- 单链表插入之不包含头节点

1.通过传地址 实现 单链表(不包含头节点)的创建

2.要插入数据 的链表 可以为空

以下代码在vs2010 测试通过:

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

#define FALSE 0
#define	TRUE  1

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

int sll_insert(Node **linkp,int new_value);
int main(void){
	Node *linkp = NULL;
	int new_value;
	int inputres,result ;
	printf("请输入要插入的值:\n");
	inputres = scanf("%d",&new_value);
	if(inputres == 0){
		return FALSE;
	} 
	result = sll_insert(&linkp,new_value);
	if(result == 0){
		return FALSE ;
	}
	while(linkp != NULL){
		printf("%d",linkp->value);
		linkp = linkp->link;
	}
	printf("\n");
	system("pause");
	return TRUE;
}

//考虑到访问到一个链表的最后一个元素 和 第一个 元素的情况
int sll_insert(Node **linkp,int new_value){
	Node *current;
	Node *previous;
	Node *new_next;

	current = *linkp;
	previous = NULL;
	while(current != NULL && current->value < new_value){
		previous = current;
		current = current->link;
	}
	new_next = (Node *)malloc(sizeof(Node));
	if(new_next == NULL){
		return FALSE;
	}
	new_next->value = new_value;
	new_next->link = current;
	if(previous == NULL){
		*linkp = new_next;
	}else{
		previous->link = new_next;
	}
	return TRUE;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值