【问题标题】:Implement functions without using tail不使用tail实现函数
【发布时间】:2017-09-08 16:53:46
【问题描述】:

我创建了一个程序来反转单词的非元音序列,用一个简单的链表表示,但我应该这样做而不使用指向最后一个节点的尾指针。

我在createListpop(用于弹出列表并返回每个节点的字母字符)、push_backpush_front(都用于反转非元音序列。例如,@ 987654325@ 将一个节点放在包含分析序列的列表前面:node-> a-> b-> c.push_back,同理,使序列 a-> b-> c 成为 a-> b-> c-> 节点)。

LIST *createList(void){
    LIST *list = malloc(sizeof(*list));
    if(list){
        list->first = list->tail = NULL;
    }
    return list;
}

char pop(LIST *list){
    char ch = list->first->letter;

    list->first = list->first->next;
    if(list->first == NULL)
        list->tail = NULL;
    return ch;
}

void push_back(LIST *list, char ch){
    NODE *node = createNode(ch);
    if(list->first)
        list->tail = list->tail->next = node;
    else
        list->tail = list->first = node;
}

void push_front(LIST *list, char ch){
    NODE *node = createNode(ch);
    if(list->first){
        node->next = list->first;
        list->first = node;
    } else {
        list->tail = list->first = node;
    }
}

我想知道如何用一些局部变量或上述函数的另一个实现来替换 typedef 中的尾指针。

【问题讨论】:

  • 您可以通过从头开始跟踪列表而不是tail指针来确定最后一个元素,但是随着列表变长,效率低下。

标签: c data-structures linked-list tail


【解决方案1】:

你只需要改变 push_back 因为它会推到列表的末尾

void push_back(LIST *list, char ch){
    NODE *node = createNode(ch);
    NODE *tmp = list->first;

    if (tmp)
      while(tmp)
      {
         if (tmp->next == NULL)
         { 
            tmp->next = node;
            tmp = tmp->next;
         }
         tmp = tmp->next;         
      }
    else
      list->first = node;
}

你可以在这里找到完整的实现https://repl.it/KiBB/6

【讨论】:

    猜你喜欢
    • 2012-02-24
    • 1970-01-01
    • 2019-04-17
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多