Question

C program prelab: This lab is pretty simple to describe: expand your suite of linked-list functions...

C program prelab:
This lab is pretty simple to describe: expand your suite of linked-list functions to include an ability to
insert a given key into a list at a particular location; or in its correct sorted-order position; or to remove a
specified key from a list or the key at a specified location. We’ve gone through the logic – though by now
you should be able to work it out on your own – and we've discussed the kinds of situations that can be
problematic. For example, what should be done if the calling program asks to remove a key that isn’t in
the list? You could have a return value telling the user it wasn't deleted, or you could have it do nothing
if the key is not in the list. As long as you provide appropriate documentation for the user then either
choice is defensible.
In the case of delete/remove, should the function remove only the first occurrence of the specified key
or all occurrences? Or should we provide separate functions for those two cases? Again, it's up to you to
decide which is more useful/convenient for the user.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

# PLEASE GIVE IT A THUMBS UP !

Below is the function that inserts a given element at a soecified position into the linkedlist.

The function takes 3 parameters as arguments the head of the linkedlist , the new element to be inserted and the position where to be inserted.

#steps:

1.) Traverse the linkedlist till position -1 th element.

2.) Assign a new node to the given element

3.)store the next of the current position element in temp variable.

4.)change the next of the current position variable to the node

5.) Assign the next of the node to the temp.

#SOURCE 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 postion

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

{

    // This condition to check whether the

    // postion given is valid or not.

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

        cout << "Invalid postion!" << endl;

    else {

  

        // Keep looping until the pos is zero

        while (pos--) {

  

            if (pos == 0) {

  

                // adding Node at required postion

                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;

}

b.) For deletion the steps are:

1.) Traverse and find the previous node of the node to be deleted.

2.)Modify the next of the previous node to the next of the node to be deleted.

3.)Free the deleted node.

#SOURCE CODE

#include <stdio.h>

#include <stdlib.h>

  

// A linked list node

struct Node

{

    int data;

    struct Node *next;

};

  

/* Given a reference (pointer to pointer) to the head of a list

   and an int, inserts a new node on the front of the list. */

void push(struct Node** head_ref, int new_data)

{

    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

    new_node->data = new_data;

    new_node->next = (*head_ref);

    (*head_ref)    = new_node;

}

  

/* Given a reference (pointer to pointer) to the head of a list

   and a key, deletes the first occurrence of key in linked list */

void deleteNode(struct Node **head_ref, int key)

{

    // Store head node

    struct Node* temp = *head_ref, *prev;

  

    // If head node itself holds the key to be deleted

    if (temp != NULL && temp->data == key)

    {

        *head_ref = temp->next;   // Changed head

        free(temp);               // free old head

        return;

    }

  

    // Search for the key to be deleted, keep track of the

    // previous node as we need to change 'prev->next'

    while (temp != NULL && temp->data != key)

    {

        prev = temp;

        temp = temp->next;

    }

  

    // If key was not present in linked list

    if (temp == NULL) return;

  

    // Unlink the node from linked list

    prev->next = temp->next;

  

    free(temp); // Free memory

}

  

// This function prints contents of linked list starting from

// the given node

void printList(struct Node *node)

{

    while (node != NULL)

    {

        printf(" %d ", node->data);

        node = node->next;

    }

}

  

/* Drier program to test above functions*/

int main()

{

    /* Start with the empty list */

    struct Node* head = NULL;

  

    push(&head, 7);

    push(&head, 1);

    push(&head, 3);

    push(&head, 2);

  

    puts("Created Linked List: ");

    printList(head);

    deleteNode(&head, 1);

    puts("\nLinked List after Deletion of 1: ");

    printList(head);

    return 0;

}

Thankyou , if any query plz comment , I will resolve it asap.

Add a comment
Know the answer?
Add Answer to:
C program prelab: This lab is pretty simple to describe: expand your suite of linked-list functions...
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
  • Please Write the following code in C: PRELAB - Week of October 14 For this prelab...

    Please Write the following code in C: PRELAB - Week of October 14 For this prelab you will implement the following functions: List * initIntegerList() // Return empty list int insertAtHead(int k, List*) // Insert k at head int insertAtTail(int k, List*) // Insert k at tail int removeHead(List *) // Remove head and return its key int getListSize(List *) // Return number of elements in list void printHead(List *) // Print key in head void moveHeadToTail(List *) // Move...

  • IN C ONLY PLZ (read the instruction carefully plz) You will implement the following functions: List...

    IN C ONLY PLZ (read the instruction carefully plz) You will implement the following functions: List * initIntegerList( ) // Return empty list int insertAtHead(int k, List*) // Insert k at head int insertAtTail(int k, List*) // Insert k at tail int removeHead(List *) // Remove head and return its key int getListSize(List *) // Return number of elements in list void printHead(List *) // Print key in head void moveHeadToTail(List *) // Move key at head to tail This...

  • In C++ syntax please Write a program that implements and demonstrates a linked list using functions....

    In C++ syntax please Write a program that implements and demonstrates a linked list using functions. Your program should first dehne a node that stores an integer and then your program will include the following functions appendo- This function accepts the head pointer (by reference) of a linked list and an integer as it's only arguments. It then creates a node, stores the integer argument in the node, and adds it to the end of the list. findo-This function accepts...

  • (C++ program) Write a game that uses linked list. There should be 20 nodes. You can...

    (C++ program) Write a game that uses linked list. There should be 20 nodes. You can change the struct to your preferences in order to make the game better. Make sure the user is not able to move to a NULL location. The story game should be rated PG-13. No bad words or gore.You can add special conditions to where the story will not progress unless you clear a certain obstacle in a different room, others did enemy encounters where...

  • I need this in C++. This is all one question Program 2: Linked List Class For...

    I need this in C++. This is all one question Program 2: Linked List Class For this problem, let us take the linked list we wrote in a functional manner in a previous assignment and convert it into a Linked List class. For extra practice with pointers we'll expand its functionality and make it a doubly linked list with the ability to traverse in both directions. Since the list is doubly linked, each node will have the following structure: struct...

  • C++ Lab 1. Read in the contents of a text file up to a maximum of...

    C++ Lab 1. Read in the contents of a text file up to a maximum of 1024 words – you create your own input. When reading the file contents, you can discard words that are single characters to avoid symbols, special characters, etc. 2. Sort the words read in ascending order in an array (you are not allowed to use Vectors) using the Selection Sort algorithm implemented in its own function. 3. Search any item input by user in your...

  • C programming A linked list is a linear data structure that allows us to add and remove items fro...

    c programming A linked list is a linear data structure that allows us to add and remove items from the list very quickly, by simply changing a few pointers. There are many different variations of linked lists. We have studied the doubly-linked, circular, with a dummy-header-node version of a linked list. In the class notes we studied several functions to manipulate a Linked List. For this assignment you must write the code for the following additional linked list functions: addFirst,...

  • Prelab Exercises Your task is to write a Java program that will print out the following...

    Prelab Exercises Your task is to write a Java program that will print out the following message (including the row of equal marks): Computer Science, Yes!!!! ========================= An outline of the program is below. Complete it as follows: a. In the documentation at the top, fill in the name of the file the program would be saved in and a brief description of what the program does. b. Add the code for the main method to do the printing. //...

  • Part 1: Implement a singly linked list -------------------------------------- (a) Your job is to implement a generic...

    Part 1: Implement a singly linked list -------------------------------------- (a) Your job is to implement a generic singly linked list that can hold any data type. The interface has been specified and provided to you in a header file called mylist.h. So your job is to write mylist.c that implements each function whose prototype is included in mylist.h. Specifically, you are asked to write the following functions: struct Node *addFront(struct List *list, void *data) void traverseList(struct List *list, void (*f)(void *))...

  • C++ Programming Question: This programming assignment is intended to demonstrate your knowledge of the following: ▪...

    C++ Programming Question: This programming assignment is intended to demonstrate your knowledge of the following: ▪ Writing a while loop ▪ Write functions and calling functions Text Processing [50 points] We would like to demonstrate our ability to control strings and use methods. There are times when a program has to search for and replace certain characters in a string with other characters. This program will look for an individual character, called the key character, inside a target string. It...

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