Write a function in C++ that will swap the second and third node in a singly linked list (having 5 nodes) by adjusting only the pointers (and not the data). You can use Node class and List class methods (such as getNext, setNext, next, get) without writing them. You can assume that the Node class and List class exists, i.e., do not write the code for these classes. The simple declaration of Node class and List class is as follow,
class Node
{
public:
int get() { return object; };
void set(int object) { this-%26gt;object = object; };
Node * getNext() { return nextNode; }; //returns the next node pointer
void setNext(Node * nextNode) { this-%26gt;nextNode = nextNode; }; // set the next node pointer
private:
int object;
Node * nextNode;
};
/* The List class */
class List
{
public:
List(); // constructor
void add (int addObject); // add the nodes in list
int get(); // returns the value of the current node
bool next(); // returns true if next node exist otherwise returns false
friend void traverse(List list); // used to print the values of all the nodes in the list
void swap();
private:
int size;
Node * headNode;
Node * currentNode;
Node * lastCurrentNode;
};
void List ::swap() // Complete this code
{
}
Write a function in C++ that will swap the second and third node in a singly linked list (having 5 nodes) by a
You'll need a temporary pointer:
Node *p = currentNode;
Now, I assume you're switching the current node with the one after it, so...
Well, even before the temporary pointer, you'll need to make sure there's a node to switch with, so...
if(!next()) return;
Because if there isn't, what're you going to do?
Back to the temporary pointer. Move the currentNode pointer ahead using getNext(). Then you can actually go about making the switch...
p's next has to become currentNode's next, and currentNode's next has to become p. So you'll use setNext...
p.setNext(currentNode.getNext());
currentNode.setNext(p);
Oh, and back at the beginning, if this will ONLY switch the second and third, make sure currentNode starts on the second one--set it equal to head, and move it forward until it's in the right place using getNext.
Aaaaand it's done.
shoe polish
No comments:
Post a Comment