Question
Writing a program which involves shifting elements of a singly linked-list up and down. There is to tail pointer, only a head pointer. I have
Writing a program which involves shifting elements of a singly linked-list up and down. There is to tail pointer, only a head pointer. I have the following code below but am unable to get it to print. Here is the description for what is suppose to happen:
shiftElementUp and shiftElementDown: These, given the location of an element (its position in the list), will move that element one position up or down the list. For example, if you shifted the element at position 5 up, it would then be in position 4, the element that was at position 4 should now be in position 5. These should be bool functions that return false if the position is not valid. Note, the first element cannot be shifted up, and the last element cannot be shifted down.
NOTE: These two functions are NOT allowed to just swap the data elements of the two nodes. They must rearrange their pointers correctly to do this job. NOTE: Positions start at 1.
Here is the code I have (note: 'nodePtr' is typedef'd for *node and 'head' is a global nodePtr) :
In Header class:
struct node { elementType item; nodePtr next; };
In .cpp file for LinkedList class:
bool LinkedList::shiftElementDown(int position) { nodePtr curPtr = head; nodePtr temp; if (position == this->size()) { return false; } else if (position == 1) { temp = curPtr->next; curPtr->next = curPtr; curPtr = temp; } else { for (int i = 1; i < position; i++) { curPtr = curPtr->next; } temp = curPtr->next; curPtr->next = curPtr; curPtr = temp; } return true; }
bool LinkedList::shiftElementUp(int position) { nodePtr curPtr = head; nodePtr temp; if (position == 1) { return false; } else { for (int i = 1; i < position - 1; i++) { curPtr = curPtr->next; } temp = curPtr->next; curPtr->next = curPtr; curPtr = temp; } return true; }
The list does not print at all for either function (the printing is called in the driver, not in either of these functions and I know that's not the issue) and am unsure on what to do. Any help is greatly appreciated. Thank you.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started