Question

In: Computer Science

this is my linkedlist and to insert a new element in it , however i want...

this is my linkedlist and to insert a new element in it , however i want it to be user entered linkedlist

#include <bits/stdc++.h>

using namespace std;

  

// A linked list Node

struct Node {

    int data;

    struct Node* next;

};

  

// Size of linked list

int size = 0;

  

// function to create and return a Node

Node* getNode(int data)

{

    // allocating space

    Node* newNode = new Node();

  

    // inserting the required data

    newNode->data = data;

    newNode->next = NULL;

    return newNode;

}

  

// function to insert a Node at required position

void insertPos(Node** current, int pos, int data)

{

    // This condition to check whether the

    // position given is valid or not.

    if (pos < 1 || pos > size + 1)

        cout << "Invalid position!" << endl;

    else {

  

        // Keep looping until the pos is zero

        while (pos--) {

  

            if (pos == 0) {

  

                // adding Node at required position

                Node* temp = getNode(data);

  

                // Making the new Node to point to

                // the old Node at the same position

                temp->next = *current;

  

                // Changing the pointer of the Node previous

                // to the old Node to point to the new Node

                *current = temp;

            }

            else

              // Assign double pointer variable to point to the

              // pointer pointing to the address of next Node

              current = &(*current)->next;

        }

        size++;

    }

}

  

// This function prints contents

// of the linked list

void printList(struct Node* head)

{

    while (head != NULL) {

        cout << " " << head->data;

        head = head->next;

    }

    cout << endl;

}

  

// Driver Code

int main()

{

    // Creating the list 3->5->8->10

    Node* head = NULL;

    head = getNode(3);

    head->next = getNode(5);

    head->next->next = getNode(8);

    head->next->next->next = getNode(10);

  

    size = 4;

  

    cout << "Linked list before insertion: ";

    printList(head);

  

    int data = 12, pos = 3;

    insertPos(&head, pos, data);

    cout << "Linked list after insertion of 12 at position 3: ";

    printList(head);

  

    // front of the linked list

    data = 1, pos = 1;

    insertPos(&head, pos, data);

    cout << "Linked list after insertion of 1 at position 1: ";

    printList(head);

  

    // insetion at end of the linked list

    data = 15, pos = 7;

    insertPos(&head, pos, data);

    cout << "Linked list after insertion of 15 at position 7: ";

    printList(head);

  

    return 0;

}

Solutions

Expert Solution

Not sure if just linkedlist is user-entered or the insertion is also user-specified. Both of them implemented, please change the insertion part to original if it is not required. Hope it helps!

The input is assuming the linked list data to be in a single line and the next lines are input for insertion in linkedlist.

The edited code is in bold.

Code:

#include <bits/stdc++.h>
using namespace std;

// A linked list Node
struct Node {

int data;
struct Node* next;

};


// Size of linked list
int size = 0;

// function to create and return a Node
Node* getNode(int data)
{

// allocating space
Node* newNode = new Node();

// inserting the required data
newNode->data = data;

newNode->next = NULL;

return newNode;

}

// function to insert a Node at required position
void insertPos(Node** current, int pos, int data)
{

// This condition to check whether the
// position given is valid or not.

if (pos < 1 || pos > size + 1)
cout << "Invalid position!" << endl;
else {
  
// Keep looping until the pos is zero
while (pos--) {

if (pos == 0) {

// adding Node at required position
Node* temp = getNode(data);

// Making the new Node to point to
// the old Node at the same position
temp->next = *current;

// Changing the pointer of the Node previous
// to the old Node to point to the new Node
*current = temp;

}
else
  
// Assign double pointer variable to point to the
// pointer pointing to the address of next Node
current = &(*current)->next;

}
size++;
}

}

// This function prints contents
// of the linked list
void printList(struct Node* head)
{

while (head != NULL) {
  
cout << " " << head->data;
head = head->next;

}
cout << endl;

}

// Driver Code
int main()
{

   // Creating an empty
   Node* head = NULL;
   int size, val;
   string line;
  
   cout<<"Enter size of linked list: ";
   cin>>size;
  
   // pass the iterator value as the position
   // at which number is to be inserted
   for(int i=1;i<=size;i++) {
  
       cin>>val;   // input element
       insertPos(&head, i, val);
   }
  
   cout << "Linked list before insertion: ";
   printList(head);
  
   // insertion part-----------------------------------------------------------
   int data, pos;
  
   while(true) {
   // ask user if they want to insert a number
   cout<<"Enter y|Y if data is to be inserted, otherwise enter anything: ";
   cin>>line;
  
   // insertion
   if(line == "y" || line == "Y") {
   cout<<"Enter data and position: ";
   cin>>data>>pos;
   // insert element
   insertPos(&head, pos, data);
  
   cout << "Linked list after insertion of "<<data<<" at position "<<pos<<": ";
   printList(head);
   } else {
   // come out of the loop if insertion is completed
   break;
   }
   }

  
   return 0;
  
}

Sample Output:

Code snippet screenshot:


Related Solutions

I am trying to create my own doubly linkedlist class and here is what I have...
I am trying to create my own doubly linkedlist class and here is what I have so far. my addfirst is adding elements forever and ever, and I could use some help. This is in C++. Please help me complete my doubly linkedlist class. the addfirst method is what I would like to complete. #ifndef DLLIST_H #define DLLIST_H #include "node.h" #include using namespace std; template class DLList { private:     Node* head = nullptr;     Node* tail = nullptr;    ...
this is my code I want the opposite i want to convert a postfix expression to...
this is my code I want the opposite i want to convert a postfix expression to infix expression #include <iostream> #include <string> #define SIZE 50 using namespace std; // structure to represent a stack struct Stack {   char s[SIZE];   int top; }; void push(Stack *st, char c) {   st->top++;   st->s[st->top] = c; } char pop(Stack *st) {   char c = st->s[st->top];   st->top--;   //(A+B)*(C+D)   return c; } /* function to check whether a character is an operator or not. this function...
I want my answer typed.                                      I. What i
I want my answer typed.                                      I. What is presbyopia? Hyperopia? Myopia? 2. Which cranial nerves assesses eye function and acoustic function? 3. What is the Rinne test? Weber test? 4. Do you or anyone you know have any of the issues/symptoms/conditions mentioned in the video? Is it due to genetics or aging? How is it being managed?
Python I want to name my hero and my alien in my code how do I...
Python I want to name my hero and my alien in my code how do I do that: Keep in mind I don't want to change my code except to give the hero and alien a name import random class Hero:     def __init__(self,ammo,health):         self.ammo=ammo         self.health=health     def blast(self):         print("The Hero blasts an Alien!")         if self.ammo>0:             self.ammo-=1             return True         else:             print("Oh no! Hero is out of ammo.")             return False     def...
I am making google slide presentation and want to insert a pdf into it and cannot...
I am making google slide presentation and want to insert a pdf into it and cannot figure out how to do it
I am currently pursuing my chemical engineering degree. I want to know, if i want work...
I am currently pursuing my chemical engineering degree. I want to know, if i want work in chemical industry in future, what are the most important Subject (specific topic) / concept which are important from industry perspective (list them). Also list some of most important book that every chemical engineer should have. Thankyou!!
What element they are: 1.My appearance at standard state is a silvery-white. My density when I...
What element they are: 1.My appearance at standard state is a silvery-white. My density when I melt is 1.46g/cm3. I burn purple, and react violently on contact with water. I see use in atomic clocks, and sometimes in glass 2.I am a diatomic molecule with a melting point of -259.14˚C and have a lower density than any other element.I am highly flammable and commonly form compounds with non-metals and halogens.I am commonly found in a product used to clean wounds...
i want a historical review on movie my name is khan
i want a historical review on movie my name is khan
Remove the minimum element from the linked list in Java public class LinkedList {      ...
Remove the minimum element from the linked list in Java public class LinkedList {       // The LinkedList Node class    private class Node{               int data;        Node next;               Node(int gdata)        {            this.data = gdata;            this.next = null;        }           }       // The LinkedList fields    Node head;       // Constructor    LinkedList(int gdata)   ...
There is something wrong with my arduino lab. I want my four leds to light up...
There is something wrong with my arduino lab. I want my four leds to light up one after the other. Then the speaker plays music, and 4 leds change with music. But my code only makes one of them work. Please help me modify my code const int switchPin = 8; unsigned long previousTime = 0; int switchState = 0; int prevSwitchState = 0; int led = 2; // 600000 = 10 minutes in milliseconds long interval = 1000; int...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT