Skip to content

Instantly share code, notes, and snippets.

@suvasish114
Created March 23, 2021 08:20
Show Gist options
  • Save suvasish114/ef85cc9643f8b602fab08df0c4b92c1c to your computer and use it in GitHub Desktop.
Save suvasish114/ef85cc9643f8b602fab08df0c4b92c1c to your computer and use it in GitHub Desktop.

delete duplicate node from a single linked list

language : C

// delete duplicate nodes from a linked list

#include<stdio.h>
#include<cstdlib>

// functions
struct NODE* createll(void);
void duplicate(struct NODE *head);
void display(struct NODE *head);

// structure
struct NODE {
	int data;
	struct NODE *link;
};

//------------------------- driving code ------------------------
int main(){
	struct NODE *l1;
	printf("enter 1st node\n");
	l1 = createll();
	printf("Linked list before delete duplicate nodes\n");
	display(l1);
	duplicate(l1);
	printf("Linked list after delete duplicate nodes\n");
	display(l1);
	return 0;
}

// -------------------------- functions -------------------------
// create nodes 
struct NODE* createll(void){
	struct NODE *ptr, *head, *temp;
	head = NULL;
	while(1){
		temp = (struct NODE*) malloc(sizeof(struct NODE));
		printf("Enter data: ");
		scanf("%d",&temp->data);
		if(head == NULL){
			head = temp;
			ptr = temp;
		}
		else{
			ptr->link = temp;
			ptr = ptr->link;
		}
		printf("enter 0 to exit, other key to make node: ");
		int x;
		scanf("%d",&x);
		if(x==0) break;
	}
	ptr->link = NULL;
	return head;
}

// remove duplicate nodes
void duplicate(struct NODE *head){
	struct NODE *ptr, *ptr1, *ptr2, *temp;
	ptr = ptr2 = head;
	ptr1 = ptr->link;
	while(ptr!=NULL){
		while(ptr1!=NULL){
			if(ptr->data == ptr1->data){
				ptr2->link = ptr1->link;
				temp = ptr1;
				free(temp);
			}
			ptr1 = ptr1->link;
			ptr2 = ptr2->link;
		}
	}
}

// display linked list 
void display(struct NODE *head){
	struct NODE *ptr ;
	ptr = head;
	while(ptr != NULL){
		printf(" %d", ptr->data);
		ptr = ptr->link;
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment