链表

/*
 * author: lx
 * date: 2011-09-08
 * brief: the interface of list
 * file: llist.c
 */

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

int
insert_list( register Node **linkp, int new_value )
{
        register Node *current;
        register Node *new;

        while ( ( current = *linkp ) != NULL &&
                current->value < new_value )
                linkp = &current->link;

        new = ( Node* )malloc( sizeof( Node ) );
        if ( new == NULL )
                return FALSE;
        new->value = new_value;

        new->link = current;
        *linkp = new;

        return TRUE;
}

Node*
search_list( register Node* L, int k )
{
        Node* x = L;

        while ( x != NULL && x->value != k )
                x = x->link;

        return x;
}


int
delate_list( register Node** L, int k )
{
        Node *d = NULL;

        if ( ( d = search_list( *L, k ) ) == NULL )
                return FALSE;

        /*
         * find the predecessor of the value k.
         */
        Node **x = L ;
        Node *p = NULL;
        while( x != NULL )
        {
                if ( ( *x )->value != k )
                {

                        p = *x;
                        x = &((*x)->link);
                }
                else
                {
                        if ( x == L )
                                *L = (*L)->link;
                        return TRUE;
                }
        }

        p->link = (*x)->link;

        free( *x );

        return TRUE;
}

  头文件:

/*
 * author: lx
 * date: 2011-09-08
 * brief: the interface of list 
 * file: llist.h
 */

#define FALSE 0
#define TRUE 1

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


/*
 * add a element into list
 *
 * return value: 0 is right, -1 is error. 
 */
int
insert_list( register Node**, int );


/*
 * search a element in the list.
 *
 * return the pointer of Node if find. else return NULL
 *
 */
Node*
search_list( register Node*, int );

/*
 * delete a element in the list.
 *
 * returen value: 0 is right, -1 is error.
 */
int
delate_list( register Node**, int );

  

例子:

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

int
main( void )
{

        Node *p = ( Node* )malloc( sizeof( Node ) );
        if ( p == NULL )
                return FALSE;

        p->link = NULL;
        p->value = 1;


        printf( "insert some elements after 1......\n" );

        insert_list( &p, 2 );
        insert_list( &p, 3 );



        Node *plist = p;
        while( plist != NULL )
        {
                printf( "value is %d\n", plist->value );
                plist = plist->link;
        }



        delate_list( &p, 1 );

        printf( "after delate.....\n" );
        plist = p;
        while( plist != NULL )
        {
                printf( "value is %d\n", plist->value );
                plist = plist->link;
        }

        exit( 0 );
}

  

posted @ 2011-09-15 16:27  lxgeek  阅读(156)  评论(0编辑  收藏  举报