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;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。