1

我有以下代码,我正在将存储的字符串转换为链表。示例: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

笔记 :

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

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;

}

谢谢!

4

2 回答 2

3

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

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

Head is at c now

所以你永远不应该移动头部,只使用临时变量来获取头部的值并移动温度。

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

它与双指针有关吗?

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

于 2015-02-09T17:50:16.140 回答
0

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;
}

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

于 2015-02-09T18:01:47.080 回答