Skip to content

Instantly share code, notes, and snippets.

@meldsza
Created October 3, 2018 13:13
Show Gist options
  • Save meldsza/2ca7503b95f720baa551bcf1a8b2243e to your computer and use it in GitHub Desktop.
Save meldsza/2ca7503b95f720baa551bcf1a8b2243e to your computer and use it in GitHub Desktop.
Singly Linked List for a list of Students with id , sem and name featuring insertion of Node at a position and delete Rear
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int id;
char name[50];
int sem;
struct node *next;
};
typedef struct node *Node;
Node createNode(int id, char *name, int sem)
{
Node newNode = (Node)malloc(sizeof(struct node));
newNode->id = id;
strcpy(newNode->name, name);
newNode->sem = sem;
newNode->next = NULL;
return newNode;
}
void deleteNode(Node x)
{
printf("Deleted ID is %d\n", x->id);
free(x);
}
void insertNodeAt(Node head)
{
int pos, id;
char name[50];
int sem;
puts("Enter the position");
scanf("%d", &pos);
pos = pos - 1;
Node current = head;
if (pos < 0)
{
puts("Invalid position");
return;
}
while (pos > 0)
{
current = current->next;
if (current == NULL)
{
puts("Invalid position");
return;
}
pos--;
}
puts("Enter id");
scanf("%d", &id);
puts("Enter name");
scanf("%s", name);
puts("Enter semester");
scanf("%d", &sem);
Node newNode = createNode(id, name, sem);
Node next = current->next;
current->next = newNode;
newNode->next = next;
}
void deleteFront(Node head)
{
if (head->next == NULL)
{
puts("List is empty");
return;
}
Node first = head->next;
Node second = first->next;
head->next = second;
deleteNode(first);
}
void display(Node head)
{
if (head->next == NULL)
{
puts("List is empty");
return;
}
Node current = head->next;
puts("Contents are");
while (current != NULL)
{
printf("ID %d\n", current->id);
printf("Name %s\n", current->name);
printf("Semester %d\n", current->sem);
current = current->next;
}
}
int main()
{
Node head = createNode(0, "", 0);
int ex = 0, choice;
while (!ex)
{
puts("Enter your choice\n1 Insert at position\n2 Delete front\n3 Display\n4 Exit");
scanf("%d", &choice);
switch (choice)
{
case 1:
insertNodeAt(head);
break;
case 2:
deleteFront(head);
break;
case 3:
display(head);
break;
default:
ex = 1;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment