把一个节点插入一个有序的链表中,本文进行了三次尝试。
/***********************************第一次*****************************/
#include <stdlib.h>
#include <stdio.h>
#include "sll_node.h"
#define FALSE 0
#define TURE 1
int sll_insert ( Node *current, int new_value )
{
Node *previous;
Node *new;
/*******************************寻找正确插入位置*****************/
while ( current->value < new_value)
{
previous = current;
current = current->link;
}
/******************为新节点分配内存******************/
new = ( Node *)malloc (sizeof (Node));
if ( new == NULL)
return FALSE;
new->value = new_value;
/***********************插入链表*********************************/
new->link = current;
previous->link = new;
return TRUE;
}
第一个插入函数只适用于单个插入,如果插入数据过多,就会出现一个很严中的问题,那就是while循环越过链表的尾部,并对一个NULL指针进行间接操作。为了解决这个问题,我们必须对current进行检测,在执行表达式current->value之前确保它不是一个NULL指针。因此,我们进行了二次尝试(本例中在链表的起始位置也插入了节点。
/************************第二次尝试***************************/
#include <stdlib.h>
#include <stdio.h>
#include "sll_node.h"
#define FALSE 0
#define TURE 1
int sll_insert ( Node **rootp, int new_value )
{
Node *current;
Node *previous;
Node *new;
curerent = *rootp;
previous = NULL;
while ( current != NULL && current->value < new_value)
{
previous = current;
current = current->link;
}
/******************为新节点分配内存******************/
new = ( Node *)malloc (sizeof (Node));
if ( new == NULL)
return FALSE;
new->value = new_value;
/***********************插入链表*********************************/
new->link = current;
if ( previous == NULL)
*rootp = new;
else
previous->link = new;
return TRUE;
}
第二次尝试当中,用一个指向root的指针作为参数传递给函数。然后,使用间接访问,函数不仅可以获得root(指向第一个节点的指针,也就是根指针)的值。但是这种情况,把起始位置当做特殊情况进行处理的。第三次尝试将解决这个问题。
#include <stdlib.h>
#include <stdio.h>
#include "sll_node.h"
#define FALSE 0
#define TURE 1
int sll_insert ( register Node **linkp, int new_value )
{
Node *current;
Node *new;
while ( (current =*linkp) != NULL && current->value < new_value)
linkp = ¤t->link;
/******************为新节点分配内存******************/
new = ( Node *)malloc (sizeof (Node));
if ( new == NULL)
return FALSE;
new->value = new_value;
/***********************插入链表*********************************/
new->link = current;
*linkp = new;
return TRUE;
}