doyoo.C 2020-04-15 18:19
浏览 350

双向链表反转问题(c++)

    void reverse() {
        node* pre = NULL;
        node* next = NULL;
        node* current = header->next;
        while (current != NULL) {
            next = current->next;
            current->next = pre;
            if (next == NULL) {
                header->next = current;
                current->pre = header;
                break;
            }
            pre = current;
            current->pre = next;
            current = next;
        }
    }
void reverse() {
    node* current = header->next;
    current->pre = NULL;
    while (current != NULL) {
        node* next = current->next;
        current->next = current->pre;
        if (next == NULL) {
            header->next = current;
            current->pre = header;
            break;
        }
        current->pre = next;
        current = next;
    }
}
void addbegin(int val) {
        node* temp = new node(val, header,header->next);
        header->next = temp;
    }

下面是node类的实现

class node {
public:
    int val;
    node* next;
    node* pre;
    node(){}
    node(int val, node* pre,node* next) {
        this->val = val;
        this->pre = pre;
        this->next = next;
    }
};

上面是我实现的双向链表的反转链表的方法

但是第二种实现方法存在一些问题,在addbegin方法使用以后再使用第二种
reverse方法,则链表的反转会出现错误
例:
现有链表为 1 2 3 4
addbegin(0)后为 0 1 2 3 4
再使用第二种reverse() 链表为4 3 2 1 0 4 3 2 1 0 4 3 2 1 0·······

但是如果不使用addbegin方法 则第二种方法的反转是正常的。
请问 问题出在哪里,debug半天也没有找出问题
(第一种实现是完全正确的,header为头结点)

  • 写回答

1条回答 默认 最新

  • doyoo.C 2021-01-20 15:44
    关注

    啊这是我npy问的,他应该已经解决了吧(挠头

    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮