c - 使用双指针将字符串转换为链表

标签 c pointers linked-list 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 的第一个代码片段中,您的插入函数存在问题,因此当您将最后一个节点插入列表时,head 指向最后一个之前的节点节点

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

Head is at c now

所以你不应该移动 head 而只是使用临时变量来获取 head 的值并移动 temp。

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

Has it something to do with the double pointer??

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

关于c - 使用双指针将字符串转换为链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28415921/

相关文章:

c++ - 为什么看起来我的对象被销毁了两次?

c++ - 在函数中获取排序数组和值并将该值放在正确的位置

c - 内存中的指针和整数表示

c - 使用链表和字符数组时出现段错误

c - 对小操作使用宏,这是好习惯吗?

android - 在 android 上使用 FFmpeg h264 解码器

c - 对于包括设置在内的小型 C 程序,合理的最少汇编指令数是多少?

c - 如何调试嵌入式进程?

java - 比较 LinkedList 中的 int 和 String

c - C 中的链表操作 Read Proof