Get smallest value from a linked list? - c++

I am currently writing a piece of code which loops through a linked list and retrieves the smallest, but is not working. Instead it seems to be returning the last value I enter into the list...
(list is the head being passed from main)
int i = 0;
Stock *node = list;
int tempSmallest = (list + 0)->itemStock;
while (node!=NULL)
{
if ((list+i)->itemStock < tempSmallest)
{
tempSmallest = node->itemStock;
node = node->nodeptr;
}
i++;
}
return list;
Thanks for any advice!

You are dereferencing (list+i) and incrementing i with every visited node for some reason. I don't know why you're doing this, but it's wrong. You basically traverse the linked list and also conceptually traverse an array (which doesn't exist at all). This is undefined behavior and cannot give meaningful results.
You must dereferece the currently valid node, not an array element that is a few indices after it somewhere in RAM, and advance by the list's next node pointer (I assume this is called nodeptr in your code?).
Something like...
Stock *node = list; // hopefully not NULL since I don't check in the next line
int smallest = node->itemStock;
while(node && node = node->nodeptr)
smallest = std::min(smallest, node->itemStock);
return smallest;

struct stock{
stock *next;
...
};
this will be the struct of your nodes.
then when you initialize them, you should refer the next pointer of the last node added, to the node you're adding currently.
then the code will be like this:
stock *node = head; // the head you passed from main
int min = node->price;
for(;node;node=node->next)
{
if(node->price < min)
min = node->price;
if(!node->next)
break();
}
return min;

Related

Indexed singly linked list

I want to create a singly linked list with. I already have an implementation that does not permit indexing on it.
I would like to add this feature but I am not sure how to do that.
So basically the head should have index "1". But I can't figure it out myself what am I supposed to do in If statement to increase the index by 1 each step.
void AddNode (int addData)
{
nodePtr NewNode = new node;
NewNode->next = NULL;
NewNode->data = addData;
if (head != NULL)
{
curr = head;
while(curr->next != NULL)
{
curr = curr->next;
}
curr->next = NewNode;
NewNode->index;
}
else
{
head = NewNode;
NewNode->index = 1;
}
}
You mean for the ability to do something like get a linked list node via a get(index)?
Also, your head should not have index 1, it should be 0. This does not comply with standard practice of zero-based indexing.
A linked list does not technically have indexes nor should it store them. It seems like a linked list might not be the right data structure for what you are doing, however you can treat it like so with a loop like this (excuse if my c++ syntax is rusty)
int get(int index) {
Node current = head;
for (int x = 0; x < index; x++) {
if (current->next == null) {
//some sort of error handling for index out of bounds
} else {
current = current->next;
}
}
return current->data
}
get(2) would return the 3rd element of the list.
Graph for the structure
Why do you want to add it to the end of the list? Just simply add the new node to the front.
I don't think it is necessary to follow the order of 1,2,3.... Instead, you can do it reversely
Before you add a new node, you visit the head and find the index(i)of it. When you add the new one, the index of this one will be i+1.
Two advantages:
- It doses not change anything when you loop through this list.
- You know how many you have added into this list.
So what you really want to do is to add the ability to index elements of a linked list.
There is no need to actually store the index anywhere (as you don't really store the index of an array/vector element as the type and the address of the first element of the array is everything you need to retrieve the i-th element).
The only information you want to keep is the length of the list since computing it is costly because you have to traverse the list from head to tail every time you need it. Once you have this information the addNode should only update the size of the list.
As you already know accessing the i-th elements of a linked list is also costly (compared to a vector), but it is easy to code.
Something like the following should work:
void get(Node* head, size_t pos) {
while (head && pos--)
head = head->next;
return pos<=0 ? head : nullptr ;
}
It traverses the list from the head until it either reaches the end (head is nullptr) or pos is <=0.
Once you are out of the loop if pos>0 means that the list is shorter than pos otherwise you can return head (which will point to the pos-th element)

Using an array of pointers-to-pointers to manipulate the pointers it points to (C++)

I've been doing this as an exercise on my own to get better at C++ (messing around with a linked list I wrote). What I want to do is to reverse the list by twisting the pointers around, rather than just 'printing' the data out in reverse (which is relatively straightforward).
I have an array of pointers-to-pointers, each pointing to a node in a linked list. But this is less a question about linked-list dynamics (which I understand), and more about pointer magick.
A node looks like this,
template<class T>
struct node {
T data;
node *next;
node(T value) : data(value), next(nullptr) {}
};
And the code in question,
node<T> **reverseArr[listLength];
node<T> *parser = root;
for (auto i : reverseArr) {
i = &parser;
parser = parser->next;
}
root = *(reverseArr[listLength - 1]);
for (int ppi = listLength - 1; ppi >= 0; --ppi) {
if (ppi == 0) {
(*reverseArr[ppi])->next = nullptr;
//std::cout << "ppi is zero!" << "\t";
}
else {
(*reverseArr[ppi])->next = (*reverseArr[ppi - 1]);
//std::cout << "ppi, 'tis not zero!" << "\t";
}
}
My logic:
The new root is the last element of the list,
Iterate through the array in reverse,
Set the current node's next pointer to the previous one by setting the current node's nextNode to the next node in the loop.
What's happening:
If I leave the debug print statements commented, nothing. The function's called but the linked list remains unchanged (not reversed)
If I uncomment the debug prints, the program seg-faults (which doesn't make a whole lot of sense to me but seems to indicate a flaw in my code)
I suspect there's something I'm missing that a fresh pair of eyes might catch. Am I, perhaps, mishandling the array (not accounting for the decay to a pointer or something)?
You're overthinking the problem. The correct way to reverse a single-linked list is much simpler than you think, and does not involve arrays at all.
All you need to do is walk through the list setting each node's next pointer to the head of the list, then set the head of the list to that node. Essentially, you are unlinking each node and inserting it at the start of the list. Once you reach the end, your list is reversed.
It just requires a bit of care, because the order that you do things is important. Something like this should do it:
template <class T>
node<T> * reverse( node<T> * head )
{
node<T> *current = head;
head = NULL;
while( current != NULL )
{
// store remainder of list
node<T> *remain = current->next;
// re-link current node at the head
current->next = head;
head = current;
// continue iterating remainder of list
current = remain;
}
return head;
}
The operation has a linear time complexity. You would invoke it by passing your list's head node as follows:
root = reverse( root );
It should go without saying that it would be a bad idea to call this function with any node that is not the head of a list, or to pass in a list that contains cycles.

Return a pointer to a sorted list; linked list in C++

i want this function sortPair to take 2 Node pointers and return a pointer to a list of the 2 elements sorted alphabetically. The code below is what I have so far. If someone could let me know where I went wrong, that would be great.
struct Node{
string val;
Node* next;
};
Node* sortPair (Node* p1, Node* p2){
//Assert that neither pointer is null
assert(p1!=NULL);
assert(p2!=NULL);
Node* head=NULL;
Node* current=NULL;
Node* last = NULL;
current = new Node();
if(p1-> val >p2-> val) //If p1->val comes before p2->val in the alphabet
{
current->val = p1->val;
head = current;
last = current;
current = new Node();
current -> val = p2->val;
last = current;
last ->next = NULL;
}
else
{
current->val = p2->val;
head = current;
last = current;
current = new Node();
current -> val = p1->val;
last = current;
last ->next = NULL;
}
return head;
}
A linked list is just a series of nodes that are linked by each element having a pointer to the next one.
From your code, it seems like you do not want to make a list of the two nodes, but rather insert a node into a list that already exists.
If all you want to do is to make a linked list of the two nodes that are there, then set the one with the lower or higher value, depending on how you sort them, to point at the other one. For example, if you are sorting from smallest to biggest, set the smallest node's next pointer to point to the bigger one and return the pointer of the smallest one.
If you want to add one of the nodes into a list of nodes, then you must loop through the list until you find one that is larger or smaller than the node you want to insert. I recommend using a while loop.
If you want to merge two lists, then you must make a new loop that inserts each element of one list into the other list.
There is no need to make a new node for any of this, just use the ones you have and change the next pointers.
Hope this helps.

inserting node function confusing

I'm trying to understand this function to insert an element into a linked list of sorted integers in ascending order, however, there are parts of the code that are confusing me...
Node* insert (int x, Node *p) {
if (p==nullptr)
return cons(x,nullptr); //inserts the new node at front of list,before node with nullptr?
if (x < = p-> val)
return cons(x,p); //this also inserts node at front of the list?
//now the rest of the function is where I get confused...
Node *prev=p; //so this is not allocating new memory, so what exactly does it mean?
Node * after=prev->next;
//prev->next is pointing at whatever after is pointing to but after has no address?
while (after!=nullptr && x > after->val) { //whats going on here?
prev=after;
after=after-> next;
}
prev->next=cons(x,after);
return p;
}
Node* insert (int x, Node *p) {
if (p==nullptr)
return cons(x,nullptr);
//inserts the new node at front of list,before node with nullptr?
if (x < = p-> val)
return cons(x,p); //this also inserts node at front of the list?
The code above takes care of inserting the new element at the beginning of the linked list. There are two instances for this to happen:
if the head, which is p in this case, is NULL.
if the element that p is pointing to has a value greater than the current element to be inserted.
Now going forward...
//now the rest of the function is where I get confused...
Node *prev=p;
//so this is not allocating new memory, so what exactly does it mean?
This is just like a temporary pointer which can be used to traverse the linked list. So you store the head 'p' in the prev pointer.
Node * after=prev->next;
//prev->next is pointing at whatever
//after is pointing to but after has no address?
This is a pointer that would store the next element of head.
while (after!=nullptr && x > after->val) { //whats going on here?
prev=after;
after=after-> next;
}
prev->next=cons(x,after);
return p;
}
Here, this looks a little buggy. You might want to do something like this, instead:
While(prev->data >= inputdata && (after->data < inputdata || after == NULL)
{
//insert your inputdata here because it is greater than the previous but less than after
// or after is NULL.
}
I hope this clarifies your confusion. Let me know if you have any questions.

C++ assigning a new address to *next in a data structure

there's something I can't get my head round...
Basically I'm given the following data structure:
struct node_ll {
int payload;
node_ll *next; //pointer to next node
};
Which is essentially a stack of numbers.
I need to create a method with the following prototype:
int tail_return(node_ll **list)
where **list is the memory address of the above data structure. My implementation is as follows:
int tail_return(node_ll **list) {
node_ll *temp;
temp = *list;
node_ll *prev_temp;
prev_temp = *list;
bool firstPass = true;
while(temp){
if(firstPass == true){
temp = temp->next;
firstPass = false;
} else {
temp = temp->next;
prev_temp = prev_temp->next;
}
}
int toReturn = prev_temp->payload;
prev_temp->payload = 0;
(**list).next = prev_temp;
delete temp;
delete prev_temp;
return toReturn;
}
However I get the following output from test runs:
List a after head insertion of 2,4,6,8,10 elements:
{10,8,6,4,2}
now removing the last element
DELETED: 2
{10,0} where it's supposed to be: {10,8,6,4}
What am I doing wrong? Apparently the method finds the right value to delete - 2. But why when I try to print it after deletion I end up with 10 and 0?
(**list).next = prev_temp;
should be
prev_temp->next = 0 ;
when you do (**list).next = prev_temp; you are manipulating the parameter which was passed to your method and not the last node in the linked list.
I am assuming that tail_return is supposed to take a linked list of node_ll 's and delete the tail element?
Yes per #Aditya , looks like the
(**list).next = prev_temp;
line is causing a problem. The reason is that you are reassigning list to point to the second to last element (prev_temp).
Deleting the last element is correctly done by
delete temp;
And also remove the line
delete prev_temp;
since that removes the second to last element too, which you want to keep.
Plus you are currently returning the second to last element. So change
int toReturn = prev_temp->payload;
to
int toReturn = temp->payload;
(**list).next = prev_temp;
is too complicated. If you write it like this
(*list)->next = prev_temp;
it now becomes clear(er) that you change the first element in the list.
This is just a small recommendation for writing clearer code. See the other answers for the solutions to your problem(s).