指针在C单链表指针 [英] pointer to pointers for singly linked list in C

查看:175
本文介绍了指针在C单链表指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对自己在C. signly链表我创建的code链接的列表如下所示的问题:

I have a question about signly linked lists in C. I've created a linked list with the code shown below :

#include <stdio.h>
#include <stdlib.h>
struct node 
{
    int data;
    struct node* next;
};

struct node *mknode(int data)
{
    struct node* np=malloc(sizeof(struct node));
    np->data=data;
    np->next=NULL;
    return np;
}

struct node * insert (struct node* list,int data)
{
    struct node *np;
    struct node*curr=list;
    struct node* prev=NULL;
    np=mknode(data);
    for(;curr &&data<curr->data;curr=curr->next )
        prev=curr;


    np->next=curr;
    if(prev)
        prev->next=np;
    else
        list=np;
    return list;
}


int main()
{
    struct node* head;
    head=malloc(sizeof(struct node));
    head=insert(head,7);
    head=insert(head,2);
    head=insert(head,4);
    printf("%d",head->data);
    printf("%d",head->next->data);
    printf("%d",head->next->next->data);
    return 0;
}

不过,当我互联网上搜索,我已经意识到,双指针用于创建链接列表,而不是一个正常的pointer.I的意思是,结构节点**列表,而不是结构节点*名单。我想知道为什么 ?哪一个是正确的,如果他们两个是真的,什么是它们之间的区别,我用我的实现与样品主我写到这里,它工作正常,但我不知道我为什么要使用指针的指针?先谢谢了。

However,While I search on internet, I've realized that, the double pointer is used for creating linked list instead of a normal pointer.I mean, struct node **list , not struct node * list . I wonder why ? Which one is correct , and If both of them is true , what is the differences between them, I used my implementation with the sample main I wrote here, and it works fine but I dont know why should I use pointer to pointers ? Thanks in advance.

推荐答案

有些人用一个指针的指针的原因是,这样的节点可以不返回一个新的指针进行更新。在你的榜样,如果你想改变头指针,你就必须创建一个新的指针,然后使头等于指针。随着双指针,你只需要释放空间,第二个指针指向,然后第二个指针更新到新的数据结构,这使原来的头指针

The reason some people use a pointer to a pointer is so that the nodes can be updated without returning a new pointer. In your example, if you wanted to change the head pointer, you would have to create a new pointer and then make head equal to that pointer. With the double pointer, you only have to free the space that the second pointer points to, and then update the second pointer to your new data structure, which keeps your original head pointer

我只是用单一的指针在我的实现。

I just use the single pointer in my implementations.

这篇关于指针在C单链表指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆