在双向链表中实现 Popback

Implementing Popback in doubly linked list

本文关键字:Popback 实现 双向链表      更新时间:2023-10-16

我能够为利用头部和尾部的双链接列表制作pop_front函数。但是当我以类似的方式创建pop_back函数时,结果似乎没有任何变化。

我正在尝试在不遍历整个列表的情况下使用尾巴。 所以我创建了指向尾巴并从那里开始的临时指针。 我在逻辑pop_front函数中缺少什么吗?

#include "pch.h"
#include <iostream>
#include <ctime>
#include <queue>
#include <vector>
using namespace std;
//Create doubly Link List
struct node {
int data;
node* next, *prev;
};

class link {
node *head, *tail;
public:
link() { head =nullptr; tail = nullptr; }
~link(){}
node *getnewnode(int data) {
node* curr = new node;
curr->data = data;
curr->next = curr->prev = nullptr;
return curr;
}
node *pushfront(int data) {
if (head == nullptr) {
return head=tail=getnewnode(data);
}
node* curr = getnewnode(data);
head->prev = curr; 
curr->next = head;
head = curr;
return head;
}
node *pushback(int data) {
if (head == nullptr) {
return head =tail= getnewnode(data);
}
node* curr = getnewnode(data);
curr->prev= tail;
tail->next = curr;
tail = curr;
return head;
}
node* popfront() {
if (head == nullptr)
return head;
node*curr = head;
head = head->next;
head->prev = head->next->prev;
delete curr;
return head;
}
node *popback() {
if (head= nullptr)
return head;
node*curr = tail;
tail = tail->prev;
//tail->prev->next = nullptr; //it did not work
delete curr;
return head;
}
void print() {
while (head) {
cout << head->data << endl;
head = head->next;
}
}
};

int main() {
link test;



cout << "n" << "n";
for (int i = 0; i < 12; i++)
test.pushfront(i);
cout << "after this pushfront:" << endl;
//test.print();
//test.popfront();
//test.popfront();
//test.popfront();
test.popback();
test.popback();
test.popback();
cout << "after this popback:" << endl;

/*
cout << "after this pushback:" << endl;
for (int i = 0; i < 12; i++)
test.pushback(i);
*/
test.print();
}

您的popfront()实现错误,这可能是您对实现popback()感到困惑的原因。

popfront()将新headprev设置为指向新head而不是nullptr(因为新head现在是列表中的第一个节点(。如果列表在弹出时只有 1 个节点,则tail不会更新到nullptr,但更重要的是尝试设置head->prev将失败,因为head现在nullptr

popback()中,if (head= nullptr)使用赋值operator=而不是比较operator==

试试这个:

node* popfront() {
if (head == nullptr)
return nullptr;
node *curr = head;
head = curr->next;
if (head)
head->prev = nullptr;
if (curr == tail)
tail = nullptr;
delete curr;
return head;
}
node *popback() {
if (tail == nullptr)
return nullptr;
node *curr = tail;
tail = curr->prev;
if (tail)
tail->next = nullptr;
if (curr == head)
head = nullptr;
delete curr;
return head;
}

此外,print()也实施错误。 它在不应该修改head时修改。 请改用本地指针,就像您在popfront()popback()中所做的那样:

void print() {
node *curr = head;
while (curr) {
cout << curr->data << endl;
curr = curr->next;
}
}