gpt4 book ai didi

c++ - 将节点添加到链表的末尾

转载 作者:行者123 更新时间:2023-11-30 01:54:29 24 4
gpt4 key购买 nike

我一直在尝试将一个项目添加到链表的末尾。我想我已经掌握了这个概念,但是我在实现代码时遇到了困难。特别是,能够遍历链表并找到尾部。这是我到目前为止所拥有的。我已经尝试了一段时间不同的东西。任何帮助将不胜感激。

##include <iostream>
using namespace std;


class node
{
public:
int data;
node *next;
};


class linkedList
{
private:
node* ptrHead;
node* ptrTail;

int size;

public:
linkedList(); //default constructor
void display();
void addFront(int);
void removeFront();
void addBack(int);
void removeBack();
};

//default constructor
linkedList::linkedList(){
size = 0;
ptrHead = ptrTail = NULL;
}
//display linked list
void linkedList::display(){
node* current = ptrHead;

while (current != NULL) {
cout << current->data << " "; //display current item
current = current->next; //move to next item
}
cout << size;
}
//add item to front of linked list
void linkedList::addFront(int addData){

node* n = new node;
n->next = ptrHead;
n->data = addData;
ptrHead = n;

size++;
}
//remove item from front of linked list
void linkedList::removeFront(){

node* n = ptrHead;
ptrHead = ptrHead->next;
delete n;

size--;
}

void linkedList::addBack(int addData){ ////work in progress


node* n = new node; //create new node
n->data = addData; //input data
n->next = NULL; //set node to point to NULL

if ( ptrTail == NULL ) // or if ( ptrTail == nullptr )
{
ptrHead = n;
ptrTail = n;
}
else
{
ptrTail->next = n;
ptrTail = n;
}

size++;
}



//this is the test code from my main function
int main()
{
//test code
linkedList list;

list.addFront(40);
list.addFront(30);
list.addFront(20);
list.addFront(10);
list.addFront(0);
list.addBack(50);
list.addBack(60);

list.display(); //50 60 7 (the 7 is the count/size of the linked list)
cout << endl;
}

最佳答案

for(int i=1; i<size; i++)
pCurrent = pCurrent->next;

pCurrent = n;

这会起作用。但是您必须将大小变量保持为链接列表的实际大小。

或者如果你想总是在最后添加元素,你可以按照以下步骤操作。保留一个额外的节点尾部并向其添加元素。

if(head == NULL)
{
head = n;
tail = n;
}
else
{
tail->next = n;
tail = tail->next;
}

关于c++ - 将节点添加到链表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21976743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com