单链表的插入

预编译

#include <stdio.h>
#include <stdlib.h>
#define status int
#define TRUE 1
#define FALSE 0

 

数据结构

typedef struct NODE{
    struct NODE *next;        /* 指向下一个结点 */
    int value;                /* 存放结点值 */
}Node, *PNode, **List;

 

插入代码

 1 /*
 2 功能描述:
 3     把一个值插入到单链表(从小到大)
 4 
 5 参数:
 6     rootp -- 指向根结点
 7     new_value -- 存放新值
 8 
 9 返回值:
10     如果插入成功,返回TRUE;否则,返回FALSE 
11 */
12 status
13 Insert( List linkp, int new_value )
14 {
15     if ( linkp == NULL ){
16         return FALSE;
17     }
18 
19     Node *current = NULL;
20 
21     /* 寻找插入位置 */
22     while ( (current = *linkp) != NULL &&  current->value <= new_value ){
23         if ( current->value == new_value ){
24             printf( "%d已存在\n", new_value );
25             return FALSE;
26         }
27 
28         linkp = &current->next;
29     }
30 
31     /* 创建新结点 */
32     Node *_new = (PNode) malloc ( sizeof( Node ) );
33     if ( _new == NULL ){
34         printf( "内存不足\n" );
35         return FALSE;
36     }
37     _new->value = new_value;
38 
39     /* 插入新结点 */
40     _new->next = current;
41     *linkp = _new;    
42     return TRUE;
43 }

 

posted @ 2015-07-09 22:33  心中的阿哲  阅读(1141)  评论(2)    收藏  举报