I'm trying to swap the location of the first and the last node using dev c++, it's an assignment for my grades.
And the following is what I've done so far. I haven't started on the swapping function because I have no idea how.
#include <iostream>
#include <cstdlib>
using namespace std;
// Node class
class Node {
int data;
public:
Node* next;
Node(int d=0){
data = d;
next=NULL;
}
int getData() const{
return data;
}
}; //class Node
void display(Node *start, Node *end)
{
// Temp pointer
Node *tmp = start;
// One node in the list
while (tmp)
{
cout << tmp->getData() << "\t";
tmp=tmp->next;
}
} //display
Node* node;
int main()
{
Node *start, *end, *head, *last, *newNode;
start = end = new Node(5);
for (int n=10; n<=35; n=n+5) {
end->next=new Node(n);
end=end->next;
}
display(start,end);
cin.get();
//delete the first node
head=start;
start = start->next;
delete(head);
display(start,end);
cin.get();
//delete the last node
last = start;
end = start->next;
while(end->next != NULL){
last = end;
end = end->next;
}
last->next = NULL;
delete(end);
display(start,end);
cin.get();
//insert value 3 in front of the node
newNode = new Node(3);
newNode->next = NULL;
newNode->next = start;
start = newNode;
display(start,end);
cin.get();
//insert value 23 in between 20 and 25
int pos = 5;
newNode = new Node(23);
Node *temp;
end = start;
for(int i=1; i<pos-1; i++){
end = end->next;
}
temp = end->next;
end->next = newNode;
newNode->next = temp;
display(start,end);
cin.get();
//here is where the swap function must be performed.
display(start,end); //to display the result
cin.get();
} //main