anonymous
2014-02-10 17:54:38 UTC
HERE ARE THE DIRECTIONS FOR MY ASSIGNMENT;
You should implement the following two functions using the given struct:
typedef struct node_{
int value;
struct node_* next;
}node;
node* insert_top(node* head, int value);
node* delete(node* head, int value);
void print(node* head);
You should write a main function, which begins by creating an empty linked list. For the remainder of the program, the user will be prompted for 5 numbers the keyboard. Every time the user enters an integer, the insert function will be called and that number will be added into a linked list at the top, this means that the new value will become the new head of the linked list. Afterwards the user will be prompted for three numbers. For each number, the delete function will be called and that number will be removed from the linked list. If the number does not exist in the list then the linked list should not be changed. After each insertion and deletion the linked list will be printed onto the screen.
Sample Output:
$ gcc prelab3.c
$ ./a.out
insert: 3
3 -> NULL
insert: 4
4 -> 3 -> NULL
insert: 1
1 -> 4 -> 3 -> NULL
insert: 2
2 -> 1 -> 4 -> 3 -> NULL
insert: 9
9 -> 2 -> 1 -> 4 -> 3 -> NULL
delete: 2
9 -> 1 -> 4 -> 3 -> NULL
delete: 4
9 -> 1 -> 3 -> NULL
delete: 10
9 -> 1 -> 3 -> NULL
HERE IS MY CODE FOR THE ASSIGNMENT
#include
#include
typedef struct node_{
int value;
struct node_* next;
}node;
node* insert_top(node* head, int value);
node* delete(node* head, int value);
void print(node* head);
int main()
{
int insertValue, deleteValue;
int x = 0;
int y = 0;
//Creating empty linked list
node *head = (node*)malloc(sizeof(node));
head->value = insertValue;
head->next = NULL;
//While loop so I only get 5 numbers from the user to input
for(x = 0; x < 5; x++){
printf("Insert: ");
scanf("%d", &insertValue);
head = insert_top(head,insertValue);
print(head);
}
for(y = 0; y < 3; y++){
printf("delete: ");
scanf("%d", &deleteValue);
//call delete function
head = delete(head,deleteValue);
print(head);
}
}
node* insert_top(node *head, int value){
node *temp = (node*)malloc(sizeof(node));
temp->value = value;
temp->next = head;
head = temp;
return head;
}
node* delete(node* head, int deleteValue){
if(head->value == deleteValue){
node* temp = head;
head = head->next;
free(temp);
}
else{
node* temp2 = head;
while(temp2->next->value != deleteValue)
temp2 = temp2->next;
node* temp3 = temp2->next;
temp2->next = temp3->next;
free(temp3);
}
return head;
}
void print(node* head){
//Declare a new node and store the value for head in it
node* new = head;
//While new at next does not eqaul NULL
while(new->next != NULL){
//If the new node is null then print null
if(new==NULL){
printf("NULL");
break;
}
//print the numbers
printf("%d", new->value);
printf(" -> ");
new = new->next;
}
printf("NULL\n");
}