簡體   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