Skip to content

Instantly share code, notes, and snippets.

@si14
Created June 13, 2011 12:45
Show Gist options
  • Save si14/1022710 to your computer and use it in GitHub Desktop.
Save si14/1022710 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct list{
int num;
struct list * next;
};
struct list * begin = NULL, * end = NULL, * p, * tmp;
int choice, el, number = 0, position, i;
void add() {
printf("\nEnter the new element: ");
scanf("%d", &el);
if (begin == NULL) {
p = (list *)malloc(sizeof(list));
begin = p;
end = p;
p->num = el;
p->next = NULL;
printf("\nReady.\n");
number++;
return;
}
printf("\nPosition of the element in the list of %d: ", number);
scanf("%d", &position);
if (position <= number) {
p = begin;
for (i = 0; i < position - 2; i++){
p = p->next;
}
tmp = p->next;
p->next = (list *)malloc(sizeof(list));
p->next->num = el;
p->next->next = tmp;
}
else {
printf("\nAdding to the end of the list.");
end->next = (list *)malloc(sizeof(list));
end = end->next;
end->num = el;
end->next = NULL;
}
printf("\nReady.\n");
number++;
return;
}
void del() {
if (begin == NULL) {
printf ("\nList is empty.\n");
return;
}
printf("\nPosition of the element to delete in the list of %d: ", number);
scanf("%d", &position);
if (position <= number) {
if(number = 1){
p = begin;
free(p);
begin = NULL;
end = NULL;
printf("\nReady.\n");
number--;
return;
}
p = begin;
for (i = 0; i < position - 1; i++) {
p = p->next;
}
tmp = p->next->next;
free(p->next);
p->next = tmp;
if(position = 1) begin = p->next;
}
else {
printf("\nDeleting the last element.");
for(p = begin; p->next = end; p = p->next);
free(p->next);
p->next = NULL;
end = p;
}
printf("\nReady.\n");
number--;
return;
}
void print() {
p = begin;
if (p == NULL) {
printf ("\nList is empty.\n");
return;
}
while (p != NULL) {
printf(" %d ", p->num);
p = p->next;
}
printf("\n");
}
int main() {
printf ("0 - print, 1 - add, 2 - delete.\n");
while(1) {
scanf("%d", &choice);
switch (choice) {
case 0 : {
print();
} break;
case 1 : {
add();
} break;
case 2 : {
del();
} break;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment