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;
}