Created
January 26, 2017 01:48
-
-
Save wesbasinger/59a643ff8c604d776c278af33a8f1dfa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <cs50.h> | |
void quit(); | |
void show_menu(); | |
void print_list(); | |
void insert_at_tail(); | |
int search(); | |
int running = 1; | |
typedef struct node | |
{ | |
int val; | |
struct node *next; | |
}node; | |
node *head; | |
int main() | |
{ | |
while(running) | |
{ | |
show_menu(); | |
int input = get_int(); | |
if (input==0) | |
{ | |
quit(); | |
} | |
else if(input==1) | |
{ | |
print_list(); | |
} | |
else if(input==2) | |
{ | |
printf("What value to insert: "); | |
int val = get_int(); | |
insert_at_tail(val); | |
} | |
else if(input==3) | |
{ | |
printf("What value would you like to find: "); | |
int val = get_int(); | |
if(search(val)) | |
{ | |
printf("Found it!\n"); | |
} | |
else | |
{ | |
printf("Did not find it!\n"); | |
} | |
} | |
} | |
} | |
void quit() | |
{ | |
running = 0; | |
printf("Bye, thanks for playing.\n"); | |
} | |
void show_menu() | |
{ | |
printf("1. Print list.\n"); | |
printf("2. Insert value at tail.\n"); | |
printf("3. Search for value.\n"); | |
printf("0. Quit to command line.\n"); | |
} | |
void print_list() | |
{ | |
if(head==NULL) | |
{ | |
printf("List empty. No elements.\n"); | |
} | |
else | |
{ | |
node* crawler = head; | |
while (crawler->next != NULL) | |
{ | |
printf("Value is: %d\n", crawler->val); | |
crawler = crawler -> next; | |
}; | |
if (crawler->next == NULL) | |
{ | |
printf("Value is: %d\n", crawler->val); | |
} | |
printf("Finished with the list.\n"); | |
} | |
} | |
void insert_at_tail(int passed_val) | |
{ | |
if(head==NULL) // list is empty, set head to this value. | |
{ | |
head = malloc(sizeof(node)); | |
head->val = passed_val; | |
head->next = NULL; | |
} | |
else | |
{ | |
node* crawler = head; | |
while(crawler->next != NULL) | |
{ | |
crawler = crawler -> next; | |
} | |
node * last = malloc(sizeof(node)); | |
crawler->next = last; | |
last->val = passed_val; | |
last -> next = NULL; | |
} | |
} | |
int search(int n) | |
{ | |
node* crawler = head; | |
while(crawler->next != NULL) | |
{ | |
if(crawler->val == n) | |
{ | |
return 1; | |
} | |
crawler = crawler->next; | |
} | |
if(crawler->next == NULL) | |
{ | |
if(crawler->val ==n) | |
{ | |
return 1; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment