-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedList.cpp
More file actions
84 lines (76 loc) · 1.69 KB
/
Copy pathlinkedList.cpp
File metadata and controls
84 lines (76 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
using std::cout;
class Node {
public:
int data;
Node* next;
};
class LinkedList{
private:
Node* head;
public:
LinkedList() { // constructor
head = NULL;
}
~LinkedList() {}; // destructor
void addNode(int val);
void reverseList();
void display();
};
// function to add node to the end of a list
void LinkedList::addNode(int val) {
Node* newnode = new Node();
newnode->data = val;
newnode->next = NULL;
if (head == NULL) { // in case this is the list's first node
head = newnode;
}
else {
Node* temp = head; // start at the head
while (temp->next != NULL) {
temp = temp->next; // go to end of list
}
temp->next = newnode; // linking to newnode
}
}
// reverse Linked List
void LinkedList::reverseList() {
Node* temp = head;
Node* nextnode = NULL;
Node* revnode = NULL;
while (temp != NULL) {
head = temp;
nextnode = temp->next;
temp->next = revnode;
revnode = temp;
temp = nextnode;
}
}
void LinkedList::display() {
if (head == NULL) {
cout << "List is empty." << '\n';
}
else {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << '\n';
}
}
int main()
{
LinkedList* list = new LinkedList();
list->addNode(100);
list->addNode(200);
list->addNode(300);
list->addNode(400);
list->addNode(500);
cout << "Linked List data" << '\n';
list->display();
list->reverseList();
cout << "Reversed Linked List data" << '\n';
list->display();
delete list;
}