Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Online C compiler to run C program online
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct {
- void *next;
- int data;
- } Node;
- Node *head = NULL;
- //add
- Node *addNode(int data) {
- Node *new = NULL;
- //2 cases
- //if head is empty/null
- if (head == NULL) {
- new = malloc(sizeof(Node));
- if (new == NULL)
- return NULL;
- new->data = data;
- head = new;
- new->next = NULL;
- }
- else {
- new = malloc(sizeof(Node));
- if (new == NULL)
- return NULL;
- new->data = data;
- new->next = head;
- head = new;
- }
- return new;
- }
- //delete
- int removeNode(int data) {
- Node *current = head;
- Node *prev = head;
- while (current != NULL) {
- if (current->data == data) {
- //if current is head
- if (current == head) {
- head = current->next;
- }
- else {
- prev->next = current->next;
- free(current);
- current = NULL;
- }
- return 1;
- }
- prev = current;
- current = current->next;
- }
- return 0;
- }
- //insert
- Node *insertNode(int data, int position) {
- Node *current = head;
- while (current != NULL && position != 0) {
- position--;
- }
- if (position != 0) {
- printf("Request position too far into list\n");
- return NULL;
- }
- Node *new = malloc(sizeof(Node));
- if (new == NULL) {
- return NULL;
- }
- new->data = data;
- new->next = current->next;
- current->next = new;
- return new;
- }
- //print node
- void printList() {
- Node *current = head;
- while (current != NULL) {
- printf("%d->", current->data);
- current = current->next;
- }
- printf("\n");
- return;
- }
- //menu options
- void printMenu() {
- printf("1. Add node\n");
- printf("2. Delete node\n");
- printf("3. Insert node\n");
- printf("4. Print node\n");
- printf("5. Quit\n");
- printf(">>");
- return;
- }
- int main() {
- int option = 1;
- int arg1 = 0;
- int arg2 = 0;
- while (option != 5) {
- printMenu();
- int num_received = scanf("%d", &option);
- if (num_received == 1 && option > 0 && option <= 5)
- {
- switch (option) {
- case 1:
- //add
- printf("Enter data to insert: ");
- scanf("%d", &arg1);
- Node *new = addNode(arg1);
- break;
- case 2:
- //delete
- printf("Enter data to delete: ");
- scanf("%d", &arg1);
- int success = removeNode(arg1);
- if (!success) {
- printf("Element not found!");
- }
- break;
- case 3:
- int option2 = 0;
- //insert
- printf("Enter data to insert: ");
- scanf("%d", &arg1);
- printf("Enter Position: ");
- scanf("%d", &arg2);
- Node *new2 = insertNode(arg1, arg2);
- if (new2 == NULL) {
- printf("Insert Failed!\n");
- }
- break;
- case 4:
- //print
- printList();
- break;
- case 5:
- break;
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement