Question

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, removeLast, clear, and set. The provided source code contains a stub for each of these functions, together with a description of what the function should do. You must complete the body of each of these functions. You must write each of these functions from scratch. You must not invoke the existing list functions. The addFirst function will insert a new data item into the list at position 0 (in front of all the items already in the list). The removeLast function deletes the last item in the list (at position size-1), and returns the data that was deleted from the List. If removeLast is invoked on an empty List, then it should output an error message, leave the list unchanged, and return the NULL pointer. The effect of the clear function is to make the List become an empty List. The set function should alter the value of the data at the specified location in the list. The size of the list remains the same. The set function should return the item that was deleted from the List (because it was overwritten by the new item). If the set function references an illegal index, then it should print an error message, and the list should be unchanged. You should implement each of these functions in the most efficient manner possible. Your function should not take O(n) time when an O(1) solution is possible. Also, the set function should be as efficient as possible. If the target location (e.g., index) is more than halfway down the linked list, then the traversal should start from the rear of the list and move leftwards.

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

typedef struct {

char *name;
char *major;

} Student;


typedef struct node { // represents one node in a Linked List

void *data; // pointer to data associated with this node
struct node *next; // pointer to next node in List
struct node *prev; // pointer to previous node in List

} Node;


typedef struct {

Node *header; // pointer to the "dummy header node" of
// the Linked List
int size; // number of nodes in the Linked List

} LinkedList;

// function proto-types
void createList ( LinkedList *someList );
void addEnd( LinkedList *someList, void *newElement );
void *delete( LinkedList *someList, int position );
int indexOf( LinkedList *someList, char *target );
void outputList( LinkedList *someList );


int main() {

LinkedList myList;

LinkedList *roster = NULL;
outputList ( roster );

roster = &myList;
createList ( roster ); // initialize the fields of the list
outputList ( roster );

Student a, b, c, d, e, f, g;

a.name = "alice"; a.major = "ART";
b.name = "bob"; b.major = "BIO";
c.name = "chad"; c.major = "CHM";
d.name = "dan"; d.major = "DNC";
e.name = "ed"; e.major = "ENG";
f.name = "fran"; f.major = "FRN";
g.name = "gian"; g.major = "GEO";

addEnd ( roster, &a );
addEnd ( roster, &b );
addEnd ( roster, &c );
addEnd ( roster, &d );

outputList ( roster );

Student *someStudent;
someStudent = delete ( roster, 1 );
printf ( "\nAfter removing position 1 the list is:\n" );
outputList ( roster );
someStudent = delete ( roster, 0 );
printf ( "\nAfter removing position 0 the list is:\n" );
outputList ( roster );
someStudent = delete ( roster, 1 );
printf ( "\nAfter removing position 1 the list is:\n" );
outputList ( roster );
someStudent = delete ( roster, 0 );
printf ( "\nAfter removing position 0 the list is:\n" );
outputList ( roster );

addEnd ( roster, &a );
addEnd ( roster, &b );
addEnd ( roster, &c );
addEnd ( roster, &d );
outputList ( roster );

int pos;
pos = indexOf ( roster, "alice" );
printf ( "\nThe position of \"alice\" is: %d\n", pos );
pos = indexOf ( roster, "bob" );
printf ( "The position of \"bob\" is: %d\n", pos );
pos = indexOf ( roster, "chad" );
printf ( "The position of \"chad\" is: %d\n", pos );
pos = indexOf ( roster, "dan" );
printf ( "The position of \"dan\" is: %d\n\n", pos );
}


// Initially the List is empty
// We must create memory for the "dummy header node"
void createList ( LinkedList *someList )
{
someList->size = 0;

someList->header = malloc ( sizeof (Node) );

someList->header->data = NULL;
someList->header->next = someList->header;
someList->header->prev = someList->header;
}

// add the new data element to the end of the List
void addEnd( LinkedList *someList, void *newData )
{
Node *lastNode = someList->header->prev;

Node *newNode = malloc ( sizeof ( Node ) );

newNode->data = newData; // set the fields of the new Node
newNode->next = someList->header;
newNode->prev = someList->header->prev;

someList->header->prev->next = newNode; // splice-in the newNode
someList->header->prev = newNode; // into the List

someList->size++;
}


// remove the item in the given positionn in the List, and
// return the data
void *delete ( LinkedList *someList, int position )
{
if ( position < 0 || position >= someList->size ) {
printf("ERROR - illegal position in the list, aborting program\n");
exit(1);
}

// walk down the list until we reach the node to be removed

Node *temp = someList->header;
for ( int i=0; i <= position; i++ )
temp = temp->next;

void *removedData = temp->data;

temp->prev->next = temp->next; // splice-out the Node
temp->next->prev = temp->prev;

someList->size--;

free( temp ); // free-up the memory of the deleted Node

return ( removedData );
}


// locate the position in the list of the Student whose name
// equals the given target.
// return -1 if not found
int indexOf( LinkedList *someList, char *target )
{
// walk down the list until we reach the Node with the given
// target name. Stop the loop if we wrap-around the list

Node *temp = someList->header->next;

int currPos = 0; // current position in the list

while ( temp != someList->header ) {

// casting is needed since temp--> data is (void *)
char *currFirstName = ( (Student *) temp->data )->name;

if ( strcmp ( currFirstName, target ) == 0 )
return currPos; // target has been found

temp = temp->next;

currPos++;
}

return ( -1 ); // target was not found in the List
}


// output the contents of the List
void outputList( LinkedList *someList )
{
if ( someList == NULL )
printf ( "The List has not been created yet\n\n" );

else if ( someList->size == 0 )
printf ( "The List is empty\n\n" );

else {
printf ( "The List is: " );

Node *temp = someList->header->next;

for ( int num = 0; num < someList->size; num++ ) {

printf("[%s, ",
( (Student *) temp->data )->name );
printf("%s], ",
( (Student *) temp->data )->major );

temp = temp->next;
}
printf ("\n\n" );
}
}

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

0 wen Belc the code hope tat have proootded nclu do stdto hs struc rede Struct node nert Fat count seturn temp;set n) suet node. Vtemp Create nede e; temp > next-9->font 11 Add new node to 4sent int yemove labt Shuet queue) clserefur n tamp -teg ko int temp int old value LT ohile empt inder xt- shile (temp inder) tempseturn oldurtue冫

Add a comment
Know the answer?
Add Answer to:
C programming A linked list is a linear data structure that allows us to add and remove items fro...
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
  • Your task is to complete the following function/functions: 1. Given a position in the linked list,...

    Your task is to complete the following function/functions: 1. Given a position in the linked list, delete the node at that position.(Silver problem - Mandatory ) 2. Print the sum of all negative elements in the linked list.(Gold problem) If you want, you can refer to the the previous recitation manual (which was on Linked Lists) to implement node deletion. #include <iostream> using namespace std; //----------- Define Node --------------------------------------------------- struct Node{ int key; Node *next; }; //----------- Define Linked List...

  • Q) Modify the class Linked List below to make it a Doubly Linked List. Name your...

    Q) Modify the class Linked List below to make it a Doubly Linked List. Name your class DoublyLinkedList. Add a method addEnd to add an integer at the end of the list and a method displayInReverse to print the list backwards. void addEnd(int x): create this method to add x to the end of the list. void displayInReverse(): create this method to display the list elements from the last item to the first one. Create a main() function to test...

  • Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time...

    Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time complexity is omitted. Any methods/functions below could be changed into something different. I was thinking of changing the method of getting size of list and maybe change from numbers to letters for nodes. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null;...

  • Doubly Linked List Is there a way to further modify/simplify/improve this program? I was thinking of maybe changing how...

    Doubly Linked List Is there a way to further modify/simplify/improve this program? I was thinking of maybe changing how to get size. I'm not sure. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null; prev = null; data = 0; } /* Constructor */ public Node(int d, Node n, Node p) { data = d; next = n; prev = p; } /* Function...

  • Using the provided Linked List template, add the following recursive functions and demonstrate them in a...

    Using the provided Linked List template, add the following recursive functions and demonstrate them in a separate cpp file. Write a recursive function to print the list in order. Write a recursive function to print the list in reverse order. Write a recursive function to print every other node in the list in order. Write a recursive function to return the number of nodes in the list. Write a Boolean function that implements the recursive version of sequential search. THIS...

  • C LANGUAGE I just need the void push() function, which inserts new node to the front...

    C LANGUAGE I just need the void push() function, which inserts new node to the front of the list #include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node *next; } Node; //Creating head a as a global Node* Node *head; /* Given a node prev_node, insert a new node after the given prev_node */ void insertAfter (Node * prev_node, int new_data) { /*1. check if the given prev_node is NULL */ if (prev_node == NULL) { printf ("the given...

  • This is a code for linked list, it is about adding a node in the middle...

    This is a code for linked list, it is about adding a node in the middle of a list, I am really confused why int i = 2? can't it be 0? Add to the Middle • Allocate memory and store data for new node Traverse to node just before the required position of new node Change next pointers to include new node in between struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; struct node *temp head; for(int...

  • **HELP** Write a function that takes a linked list of items and deletes all repetitions from the ...

    **HELP** Write a function that takes a linked list of items and deletes all repetitions from the list. In your implementation, assume that items can be compared for equality using ==, that you used in the lab. The prototype may look like: void delete_repetitions(LinkedList& list); ** Node.h ** #ifndef Node_h #define Node_h class Node { public: // TYPEDEF typedef double value_type; // CONSTRUCTOR Node(const value_type& init_data = value_type( ), Node* init_link = NULL) { data_field = init_data; link_field = init_link;...

  • Need some help creating a bubble sort for my linked list in C. Here are the...

    Need some help creating a bubble sort for my linked list in C. Here are the structs used in my code: struct simulation {    void *list;    int et; /* in seconds */ }; struct plane {    double x, y, altitude;    char callsign[15];    struct simulation *sim; }; Here is the struct used in my linked list: struct Node {    void *data;    struct Node *next; }; Here is my insert function: //ComparisonFunction and FILE not...

  • #include <iostream> using namespace std; struct ListNode { float value; ListNode *next; }; ...

    #include <iostream> using namespace std; struct ListNode { float value; ListNode *next; }; ListNode *head; class LinkedList { public: int insertNode(float num); void deleteNode(float num); void destroyList(); void displayList(); LinkedList(void) {head = NULL;} ~LinkedList(void) {destroyList();} }; int LinkedList::insertNode(float num) { struct ListNode *newNode, *nodePtr = head, *prevNodePtr = NULL; newNode = new ListNode; if(newNode == NULL) { cout << "Error allocating memory for new list member!\n"; return 1; } newNode->value = num; newNode->next = NULL; if(head==NULL) { cout << "List...

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