LinkedList.h
#pragma once
struct Node
{
int value = 0;
Node* next = nullptr;
};
class LinkedList
{
private:
Node* first = nullptr;
public:
~LinkedList();
void add_node(int);
int get(int index);
void reverse();
};
inline LinkedList::~LinkedList()
{
Node* p = first;
Node* j = nullptr;
while (p != nullptr)
{
j = p;
p = p->next;
delete j;
}
}
inline void LinkedList::add_node(int value)
{
auto new_node = new Node;
new_node->value = value;
new_node->next = first;
first = new_node;
}
inline int LinkedList::get(int index)
{
if (first == nullptr) return -1;
Node* p = first;
for (int i = 0; i != index; ++i) {
p = p->next;
if (p == nullptr) return -1;
}
return p->value;
}
inline void LinkedList::reverse()
{
Node* p = nullptr;
Node* q = nullptr;
Node* j = first;
while (j != nullptr) {
//slide helper ptr
p = q;
q = j;
j = j->next;
//reverse node ptr
q->next = p;
}
first = q;
}
Main function
#include <iostream>
#include "LinkedList.h"
using namespace std;
int main()
{
LinkedList list;
list.add_node(8);
list.add_node(7);
list.add_node(6);
cout << list.get(0) << endl;
list.reverse();
cout << list.get(0) << endl;
}
输出结果:
6
8