New Update Launched Contact Us Download Now!

Reverse String using linked list in C

Please wait 0 seconds...
Scroll Down and click on Go to Link for destination
Congrats! Link is Generated


Hi everyone, welcome back to DataVoid! In today's video, we're going to learn about reversing a string using a doubly linked list in C. Let's get started!

First, we'll define our linked list structure. In this case, we're using a doubly linked list, so each node will have two pointers, one to the previous node and one to the next node.

Next, we'll write a function to create a new node for each character in the input string. This function will take in a pointer to the head of the linked list and the character to be added, and it will insert the new node at the beginning of the linked list.

Now, we'll write a function to print the linked list. This function will traverse the linked list from the head to the tail, printing each character along the way.

Finally, we'll write our main function, which will prompt the user for an input string, create a linked list for that string, and print the reversed string by calling the print function.

Let's try this out! Here's the code:


#include 
#include 
#include 
struct node
	{
	char data;
	struct node* pre;
	struct node* next;
	};

void create(struct node **ptr,char ch)
{
	struct node* new=(struct node*)malloc(sizeof(struct node));
	new->data= ch;
	new->pre =NULL;
	new->next=*ptr;
	if(*ptr !=NULL)
		{
		(*ptr)->pre=new;
		}
        *ptr=new;
}

void print(struct node* ptr)
{
while(ptr!=NULL)
{
printf("%c",ptr->data);
ptr= ptr->next;
}
}

void main()
{
	struct node* head=NULL;
	char s[100];
	int i;
	printf("Enter a string: ");
	scanf("%s",s);
	for(i=0;s[i]!='\0';i++)
		{
		create(&head,s[i]);
		}
	printf("The reversed string is: ");
	print(head);	
}

As you can see, when we run the program and enter the string "hello", it outputs "olleh", which is the reverse of the original string.

That's it for this video! I hope you found it helpful. If you have any questions or comments, please leave them in the comment section below. Don't forget to like and subscribe for more videos like this. Thanks for watching!

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.