这个链表代码是一个好习惯吗?

时间:2013-09-27 04:37:24

标签: c pointers linked-list

大家好我是C的新手并试图学习它。我有一个关于这个链表实现的简单查询,我在很多地方找到了它:

void addNode(node **listhead, int data, int pos){
        if(pos<=0 || pos > length(*listhead)+1){
                printf("Invalid position provided, there are currently %d nodes in the list \n", length(*listhead));
                return;
        }else{
                node *current = *listhead;
                node *newNode = (node*)malloc(sizeof(node));
                if(newNode == NULL){
                        printf("Memory allocation error\n");
                        return;
                }
                newNode->data = data;
                newNode->next = NULL;
                if (current == NULL){
                        *listhead = newNode;
                        return;
                }else{
                        int i = 0;
                        while(current->next != NULL && i < pos-1){
                                ++i;
                                current = current->next;
                        }
                        if(current->next == NULL){
                                current->next = newNode;
                        }
                        if(i == pos-1){
                                newNode->next = current->next;
                                current->next = newNode;
                        }
                }
        }
}




int main(){
        node *head = NULL;
        node **headref = &head;
        addNode(headref, 1, 1);
        addNode(headref, 2, 2);
        addNode(headref, 3, 3);
        printList(head);
        return 0;
    }

我的查询在这里我们正在创建指向指向NULL的指针的指针。这段代码有效,但我想知道这是不是一个好习惯。如果不是,我应该如何创建我的头指针并将其引用传递给addNode函数。

3 个答案:

答案 0 :(得分:2)

建议的替代方案:

int main() {
  node *head = addNode(NULL, 1, 1);
  node *current = head;
  current = addNode(current, 2, 2);
  current = addNode(current, 3, 3);
  printList(head);
  return 0;
}

换句话说:

1)addNode()成为一个将当前值作为参数的函数(所以它不必遍历整个列表只是为了添加一个新元素)...

2)...并返回指向新节点的指针。

3)这意味着在程序的 ANY 点你可以访问a)列表头的 ANY ,b)前一个指针(在“add”之前)和/或c)下一个指针(添加后)。

答案 1 :(得分:0)

我们将一个双指针传递给addNode()用于需要更新headref指针的情况。对于这种情况,使用“addNode(headref,1,1);”,addNode很可能将malloced元素的地址存储在headref中的addNode()内。如果您将headref作为指针传递,那么在调用headref之后将继续指向main中的地址,您将丢失malloced地址。

答案 2 :(得分:0)

对于单链表,它实际上是一种很好的做法,它简化了addNode实现。 我想调用addNode(node_x, 1, 1)会在node_x之前添加一个节点。如果只传递指向node_x的指针。然后,函数将需要遍历整个列表并在node_x之前找到节点并修改其指向新构造节点的指针。如果你将指针传递给指针,让我们说node** p,那么该函数只需要将新节点的地址分配给*p

相关问题