繁体   English   中英

使用双指针链接到链表的字符串

[英]String to linked list using double pointer

我有以下代码我“转换存储到链表中的字符串。例如:ABC A-> B-> C-> NULL

问题 :打印列表时,它没有提供所需的输出。以下是代码和示例输入/输出。

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    char ch;
    struct node *next;
}node;
void create(node **head,char ch)
{
    node *new;
    new=malloc(sizeof(node));
    new->next=NULL;
    new->ch=ch;
    if(*head==NULL)
    {
        *head=new;
        printf("%c",(*head)->ch);
        return ;
    }
    while((*head)->next)
    {
        (*head)=(*head)->next;
    }
    (*head)->next=new;


}
void printList(node *head)
{
    printf("\nThe list has - ");
    while(head)
    {
        printf("%c",head->ch);
        head=head->next;
    }
    printf("\n\n");
}
int main()
{
    node *head=NULL;
    int i=0;
    char *str=NULL;
    str=malloc(sizeof(char)*15);
    printf("\nEnter the string - ");
    scanf("%s",str);

    while(str[i]!='\0')
    {
        create(&head,str[i]);
        i++;
    }
    printList(head);
    return 0;
}

输入/输出样本

输入1

Enter the string - abc 
a
The list has - bc

输入2

Enter the string - abcde
a
The list has - de

输入3

Enter the string - ab
a
The list has - ab

注意 :

如果我将我的创建功能更改为此,一切正常! 我想知道这里的区别是什么? 它与双指针有关吗?

void create(node **head,char ch)
{
    node *new,*ptr;
    new=malloc(sizeof(node));
    new->next=NULL;
    new->ch=ch;
    ptr=*head;
    if(ptr==NULL)
    {
        ptr=new;
        return;
    }
    while(ptr->next)
    {
        ptr=ptr->next;
    }
    ptr->next=new;

}

谢谢!

在第一个代码段中你的插入函数存在一个问题,你移动*head所以当你将最后一个节点插入列表时头部指向最后一个节点之前的一个

a->b->c->d
      |
      |

Head is at c now

因此,您永远不应该移动头部,只需使用临时变量来获取head的值并移动temp。

a->b->c->d
|     |
|     |
Head  temp

它与双指针有关吗?

不,只是在第二个片段中,您使用ptr作为临时指针并且不移动头,您的代码如上所示。

Gopi已经指出了你的代码的问题。 如果区分将第一个节点插入空列表(在这种情况下必须更新head )和附加到现有列表的两种情况,则可以使用该建议插入新节点。 (你已经抓住了这两个案例。)

但是指向指针的策略增加了一个间接级别,你可以在这里使用它而没有这种区别: head保存指向头节点的指针。 如果使用head来遍历列表, head应始终指向指向当前节点的指针。 当前节点为NULL ,分配新节点,即覆盖指针:

void create(node **head, char ch)
{
    /* create new node */
    node *nd = malloc(sizeof(*nd));
    nd->next=NULL;
    nd->ch=ch;

    /* advance to end of list */
    while (*head) {
        head = &(*head)->next;
    }

    /* assign */
    *head = nd;
}

顺便说一句,你的第二个功能不能正常工作,因为你永远不会更新头部。 你会得到一个空列表和内存泄漏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM