posts - 63, comments - 37, trackbacks - 0, articles - 0
  IT博客 :: 首页 :: 新随笔 :: 联系 ::  :: 管理

链表操作的正确与错误的算法 重要

Posted on 2006-06-22 22:13 Enjoy Life 阅读(239) 评论(0)  编辑 收藏 引用 所属分类: DS study

通过一个子函数的内部来对单链表的头指针做修改:

1 、以下代码不能达到预期的效果:

typedef int ElemType;

typedef struct ListNode {

    ElemType data;

    struct LNode *next;

}LNode;

 

int BadInsert(LNode *head)

{

    LNode *NewL;

    NewL = (LNode *)malloc(sizeof(LNode));

    if(!NewL){

        printf("Malloc ERROR\n");

        return ERROR;

    }

    NewL->next = head;

   

    /*Incorrectly updates local copy of head.

    *Calling code retains the old values for the first element

    *pointer, so it now points at the second element of the list

    */

    /* 下面的代码只是修改了head的一个副本,并没有修改实际传进来的

    * 参数head,从而并没有达到预期的效果

    */

    head = NewL;

    return 1;

}

 

2. 正确的代码

 

int Insert(LNode **head)

{

    LNode *NewL;

    NewL = (LNode *)malloc(sizeof(LNode));

    if(!NewL)

        return 0;

    NewL->next = *head;

    /* *head gives the calling function's head pointer, so

    *the change is not lost when this function returns

    */

    *head = NewL;

    return 1;

}

只有注册用户登录后才能发表评论。