Question

Arrays, Lists, Stacks and Queues: 1) Write C++ code to reverse a singly-linked list L using...

Arrays, Lists, Stacks and Queues:

1) Write C++ code to reverse a singly-linked list L using only a constant amount of additional storage and no recursion. Assume the list object has a head pointer _head and consists of Node objects; a Node object has a pointer Node* _next

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code Screenshot:

Code Output:

Code:

#include<bits/stdc++.h>
using namespace std;
// Structure to store a linked list Node
struct Node
{
int value;
struct Node *_next;
};

void
push_front (struct Node **_head, int value)
{
struct Node *new_node = (struct Node *) malloc (sizeof (struct Node));
new_node->value = value;
new_node->_next = *_head;
*_head = new_node;
}

// reverse linked list iteratively
void reverse_list (struct Node **_head)
{
struct Node *previous = NULL;
struct Node *current = *_head;
// iterate through the list
while (current != NULL)
{
// store next of current in next
struct Node *next = current->_next;
// move the current node onto the previous
current->_next = previous;
previous = current;
// process next node
current = next;
}
// set head pointer
*_head = previous;
}

int main ()
{
int n;
cout << "Enter no of node in linked list";
cin >> n;
int i, value;
struct Node *_head = NULL;
for (i = 0; i < n; i++)
{
cin >> value;
push_front (&_head, value);
  
}
cout << "Linked list Initially:\n";
struct Node *temp = _head;
while (temp)
{
cout<< temp->value<<"->";
temp = temp->_next;
}
cout<<"Null";
reverse_list (&_head);
cout << "\nLinked list after reverse:\n";

temp = _head;
while (temp)
{
cout<< temp->value<<"->";
temp = temp->_next;
}
cout<<"Null";

return 0;
}

//Please Thumbs Up if it helps you:)

Add a comment
Know the answer?
Add Answer to:
Arrays, Lists, Stacks and Queues: 1) Write C++ code to reverse a singly-linked list L using...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT