【问题标题】:Insert a linked list into another linked list将一个链表插入另一个链表
【发布时间】:2013-06-29 19:23:44
【问题描述】:

我有一个由这样的字符组成的链接列表...

node1 - "p"
    node2 - "o"
        node3 - "p"

我需要一个包含三个参数的函数...

node *replaceChar(node *head, char key, char *str)

此功能的规定。 head 是列表的头部,'key' 和 'str' 保证只包含字母数字字符(A-Z、a-z 和 0-9)。 str 的范围可以从 1 到 1023 个字符(含)。

所以如果我用这些参数调用这个函数..

node *head == /*the head of the list to be examined*/

char key == "p"

char *str == "dog"

新列表将如下所示...

node1 - 'd'
    node2 - 'o'
        node3 - 'g'
            node4 - 'o'
                node5 - 'd'
                    node6 - 'o'
                        node7 - 'g'

“p”的所有实例都被替换为“dog”

我有一个 toString 函数,它接收一个字符串并将其转换为一个链表并返回头部。所以假设你可以调用 str = "dog" 上的函数,所以......

toString(str) == /*this will return the head to the list made from the str*/

如果不清楚我的问题...新列表适合旧列表而不丢失指针正在杀死我。

我已经尝试过了...

while(head->data != NULL)
    {
        if(head->data == key)
           { 
               node *newListHead = toString(str);

               head = newListHead;

               /*here I lose track of the old list*/

【问题讨论】:

  • 你遇到的问题是?
  • 我在问题正文的最后几行重申了我的问题。
  • 我不知道...@JoachimPileborg
  • 好的,谢谢观看
  • 那么,你有什么尝试?

标签: c list pointers linked-list head


【解决方案1】:

你可以这样开始:

node *replaceChar(node *head, char key, char *str) 
{
    node *cur, prev;
    for (cur = head, prev = NULL; cur != NULL; prev = cur, cur = cur->next)
        if (cur->ch == key) {
            node *hstart = toString(str);
            for (node *hend = hstart; hend->next != NULL; hend = hend->next)
                ;
            if (prev == NULL)
                head = hstart;
            else
                prev->next = hstart;
            hend->next = cur->next;
            free(cur);
        }

}

我的假设: 你的节点结构是这样的:

sturct node {
    char ch;
    struct node* next;
};

toString(str) 工作得很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    相关资源
    最近更新 更多