C DERS 29: SINGLE LINKED LIST

main.c

//sol tarafta projecten projenin adına sağ tıklayıp new file yapıyoruz
//sonra singlelinkedlist.c ve singlelinked.h oluşturuyoruz

#include <stdio.h>
#include <stdlib.h>
#include "singlelinkedlist.h"
 
int sayi;
int main(int argc, char *argv[]) {
	printf("Bitirmek icin 0 giriniz.n");
	do{
		printf("Sayi giriniz : ");
		scanf("%d",&sayi);
		add_last(sayi);
	}while(sayi>0);
	list();
	printf("nAranacak data? : ");
	scanf("%d",&sayi);
	int ret=find(sayi);
	if(ret<0)
		printf("Data bulunamadin");
	else
	printf("Aranan data %d.indexten",ret);
	
	printf("Silinecek data? : ");
	scanf("%d",&sayi);
	del_data(sayi);
	list();
	destroy();
	list();
	return 0;
}

singlelinkedlist.c

#include "singlelinkedlist.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
	int data;
	struct node *next;
}node_t;
 
node_t *root=NULL;
void add_last(int data){
	if(root==NULL)
	{
		root=(node_t*)malloc(sizeof(node_t));
		if(root==NULL)
		{
			printf("Yetersiz bellekn");
			return;
		}
		root->data=data;
		root->next=NULL;
	}
	else{
		node_t *tmp=root;
		while(tmp->next) tmp=tmp->next; 
		node_t *node = (node_t*)malloc(sizeof(node_t));
		if(node==NULL)
		{
			printf("Yetersiz bellek");
			return;
		}
		node->data=data;
		node->next=NULL;
		tmp->next=node;
	}
}
void list()
{
	node_t *tmp=root;
	while(tmp){
		printf("%d ",tmp->data);
		tmp=tmp->next;
	}
}
int find(int data){
	node_t *tmp=root;
	int index=0;
	while(tmp)
	{
		if(tmp->data==data)
			return index;
		tmp=tmp->next;
		index++;
	}
	return -1;
}
void del_data(int data)
{
	int found=0;
	node_t *tmp=root;
	node_t *prev=NULL;
	while(tmp)
	{
		if(tmp->data==data) {
		found=1;
		break;
		}
	prev=tmp;
	tmp=tmp->next;
	}
	if(found)
	{
		if(prev==NULL)
			root=root->next; 
		else
			prev->next=tmp->next; 
		free(tmp);
	}
}
void destroy(){
	node_t *tmp=root;
	node_t *prev=NULL;
	while(tmp)
	{
		prev=tmp;
		tmp=tmp->next;
		free(prev);
	}
	root=NULL;
}

singlelinkedlist.h

void list();
void add_last(int data);
int find(int data);
void del_data(int data);
void destroy();