Skip to content

Instantly share code, notes, and snippets.

@eroltutumlu
Last active August 29, 2015 14:16
Show Gist options
  • Save eroltutumlu/eeccb358b2d4d73db820 to your computer and use it in GitHub Desktop.
Save eroltutumlu/eeccb358b2d4d73db820 to your computer and use it in GitHub Desktop.
Singly Linked Lists in C
#include <stdio.h>
#include <stdlib.h>
struct listNode{
int id;
char name[10];
struct listNode *nextPtr;
};
typedef struct listNode ListNode;
ListNode *head, *previousPtr, *newNode, *p;
void printMenu(void);
void createLinkedList();
void traverseTheList();
void insertNode();
void deleteNode();
int main()
{
int opt;
printMenu();
createLinkedList();
printf("Choice: ");
scanf("%d",&opt);
while(opt != 4){
switch(opt){
case 1:insertNode();
break;
case 2:deleteNode();
break;
case 3:traverseTheList();
break;
default:printf("Invalid key.\n");
break;
}
printMenu();
printf("Choice: ");
scanf("%d",&opt);
}
return 0;
}
void printMenu(){
printf("Enter your choice:\n\n 1-Insert an element into the list.\n 2-Delete an element from the list\n 3-Traverse the list\n 4-Exit\n\n");
}
void createLinkedList(){
int nStudent,i;
printf("Student size: ");
scanf("%d",&nStudent);
for(i = 0; i < nStudent; i++){
if( i == 0){
p = malloc(sizeof(ListNode));
head = p;
}
else{
p->nextPtr = malloc(sizeof(ListNode));
p = p->nextPtr;
}
printf("\nID: ");
scanf("%d",&p->id);
printf("Name: ");
scanf("%s",p->name);
}
printf("\n\n");
p->nextPtr = NULL;
}
void traverseTheList(){
p = head;
while( p != NULL ){
printf(" Student ID: %d\n Student name:%s\n",p->id,p->name);
p = p->nextPtr;
printf("\n");
}
}
void insertNode(){
int recordNo;
printf("Which ID: ");
scanf("%d",&recordNo);
newNode = malloc(sizeof(ListNode));
printf("\n");
printf("ID: ");
scanf("%d",&newNode->id);
printf("Name: ");
scanf("%s",newNode->name);
printf("\n\n");
p = head;
if( p->id == recordNo ){
newNode->nextPtr = p; // Listemizin başına ekliyoruz
head = newNode; // p(Gezici pointerimiz) head'i gösteriyor.
} // Artık head yeni düğüm oldu.
else{
while( p->nextPtr != NULL && p->id != recordNo){
previousPtr = p;
p = p->nextPtr;
}
if( p == NULL ){ //Sondan eleman ekle (NULL DEGER)
previousPtr->nextPtr = newNode;
newNode->nextPtr = NULL;
}
else if( p->id == recordNo ){
newNode->nextPtr = p;
previousPtr->nextPtr = newNode;
}
}
}
void deleteNode(){
int recordNo;
printf("Which ID: ");
scanf("%d",&recordNo);
p = head;
if( p->id == recordNo ){
head = p->nextPtr;
free(p);
}
else{
while(p->nextPtr != NULL && p->id != recordNo){
previousPtr = p;
p = p->nextPtr;
}
if( p == NULL ){
printf("No elements");
}
else if(p->id == recordNo){
previousPtr->nextPtr = p->nextPtr;
free(p);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment