reverse a linked-list(C++)

#include<iostream>
using namespace std;
class Node
{
public:
Node(int value) : value(value), next(NULL) {}
public:
int value;
Node* next;
};
Node* reverseList(Node* head)
{
Node* newList = NULL;
Node* current = head;
while (current)
{
Node* next = current->next;
current->next = newList;
newList = current;
current = next;
}
return newList;
}
void printList(Node* head);
void listTests()
{
Node* one = new Node(1);
Node* two = new Node(2);
Node* three = new Node(3);
Node* four = new Node(4);
Node* five = new Node(5);
one->next = two;
two->next = three;
three->next = four;
four->next = five;
Node* head = one;
printList(head);
head = reverseList(head);
printList(head);
head = reverseList(head);
printList(head);
// cleanup memory
Node* current = head;
while (current)
{
Node* next = current->next;
delete current;
current = next;
}
}
void printList(Node* head)
{
Node* current = head;
while (current)
{
cout << current->value;
current = current->next;
}
cout << endl;
}

int main(){
listTests();
return 0;
}

reverse a linked-list(C++),布布扣,bubuko.com

reverse a linked-list(C++)

上一篇:java null


下一篇:TensorFlow 2 quickstart for beginners