以下是将问题中给出的代码转换为最基本的锻炼程序:
class myLinkedList {
private:
myLinkedList* next;
int m_value;
public:
myLinkedList() : next(0), m_value(0) { }
int getValue() const { return m_value; }
void setValue(int value) { m_value = value; }
void addNext(int value) { next = new myLinkedList; next->setValue(value); }
const myLinkedList *getNext() const { return next; }
};
#include <iostream>
static void print_list(const myLinkedList *rover)
{
std::cout << "List:";
while (rover != 0)
{
std::cout << " " << rover->getValue();
rover = rover->getNext();
}
std::cout << std::endl;
}
int main()
{
myLinkedList mine;
print_list(&mine);
mine.addNext(13);
print_list(&mine);
mine.addNext(14);
print_list(&mine);
mine.setValue(3);
print_list(&mine);
mine.addNext(15);
print_list(&mine);
}
该程序的输出是:
List: 0
List: 0 13
List: 0 14
List: 3 14
List: 3 15
如您所见,它不是普通的链表;它是最多两个项目的列表。在 下运行程序(称为ll
链表)valgrind
,我得到:
==31288== Memcheck, a memory error detector
==31288== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==31288== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==31288== Command: ll
==31288==
List: 0
List: 0 13
List: 0 14
List: 3 14
List: 3 15
==31288==
==31288== HEAP SUMMARY:
==31288== in use at exit: 6,239 bytes in 36 blocks
==31288== total heap usage: 36 allocs, 0 frees, 6,239 bytes allocated
==31288==
==31288== LEAK SUMMARY:
==31288== definitely lost: 48 bytes in 3 blocks
==31288== indirectly lost: 0 bytes in 0 blocks
==31288== possibly lost: 0 bytes in 0 blocks
==31288== still reachable: 6,191 bytes in 33 blocks
==31288== suppressed: 0 bytes in 0 blocks
==31288== Rerun with --leak-check=full to see details of leaked memory
==31288==
==31288== For counts of detected and suppressed errors, rerun with: -v
==31288== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1)
如果代码是一个有效的链表实现,那么在addNext()
.
基本上,您创建一个节点,new
然后需要将其挂接到列表中。如果另一个线程同时尝试执行此操作,则您有一个可能导致结构不一致的时间窗口。为了线程安全,您需要在修改列表时确保互斥。