【问题标题】:Reverse fuction for singly linked list isn't working as it should单链表的反向功能无法正常工作
【发布时间】:2021-02-27 02:35:29
【问题描述】:

我们给了一个任务来反转一个单链表,但出于某种原因,我正在努力解决它 它应该反转,但是应该是尾巴的头部消失了,我不知道为什么,即使在调试之后

'''

void Reverse(struct node *head) {
    struct node *last = NULL;
    struct node *current = NULL;
    struct node *temp = NULL;
    current = head;
    while (current->next != NULL) {    //getting ptr to last item of the list
        current = current->next;
        last = current;
    };
    current = head;                    //resseting the current ptr back to the head of the list
    while (current->next->next != NULL) {        //getting the current ptr to one before the tail item
        current = current->next;
    };
    temp = last;
    while (last != head) {
        if (current->next == last) {
            last->next = current;
            last = current;
            current = head;
            if (last == head) {
                head->next = NULL;;
                head->data = temp->data;
                head->next = temp->next;
                break;
            };
        };
    };
};

'''

【问题讨论】:

  • 任何反转列表的函数都需要改变头部,并以某种方式返回它。你什么都没做。

标签: c data-structures singly-linked-list


【解决方案1】:

我无法完全遵循您代码中的逻辑。你找到最后一个和倒数第二个元素,我会假设head 是你一直拥有的一些虚拟元素(因为否则,不检查它是否是NULL 是一个问题)。在那之后,我不确定会发生什么。如果您正在查看您更新的头部,您“翻转”了最后两个链接吗? (在两行之后更新之前,您无需将 head->next 设置为 NULL;这没有任何作用)。

您是否要将currenthead 移动到循环中某个位置的last 之前的那个?我认为这可行,但你会得到一个二次时间算法。

如果我们假设 head 是一个虚拟对象,所以它没有任何需要担心的元素,我们只希望它的 next 指针指向反向链接,您应该能够执行类似的操作这个:

void reverse(struct node *head)
{
  struct node *next = head->next;
  head->next = 0;
  while (next) {
    struct node *next_next = next->next;
    next->next = head->next;
    head->next = next;
    next = next_next;
  }
}

while-loop 中,您可以将代码视为将next 推到head->next 指向的列表的前面并将其从当前列表中弹出(通过将next 设置为next_next . 当您到达列表末尾时,head->next 以相反的顺序指向所有链接。(我还没有测试过代码,但我相信它应该可以工作)。

如果head不是一个虚拟节点,你必须处理它是NULL的特殊情况,你必须移动它的值。如果你必须做后者,这会让事情变得更棘手,特别是如果你想通用地使用列表,允许用户分配链接,并且你可能不知道其中有什么数据(除了它们嵌入了一个链接他们)。如果可以的话,我会选择一个虚拟链接,它使一切变得更简单,而不仅仅是反转。

当然,使用双向链表会变得更简单:

#define swap_p(x,y) \
  do { struct node *tmp = x; x = y; y = tmp; } while(0)

void reverse(node *dummy)
{
  struct link *p = dummy;
  do {
    swap_p(p->prev, p->next);
    p = p->prev;
  } while (p != dummy);
}

但这可能不是你想要的。

不知道这是否有帮助,但我希望它至少有一点作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 2017-03-16
    相关资源
    最近更新 更多