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!