Sunday 18 September 2016

Compare two strings represented as linked lists


Compare two strings represented as linked lists

Compare-List
Compare Strings









#include<iostream>
#include<stdio.h>
using namespace std;

typedef struct Node
{
    char data;
    struct Node *next;
}node;

node *CreateList(node* head, char d);
void display(node *head);
int comparelistString(node *list1, node *list2);

int main()
{
    node *list1  = NULL;
    node *list2 =  NULL;
    list1 = CreateList(list1,'g');
    CreateList(list1,'e');
    CreateList(list1,'e');
    CreateList(list1,'k');
    CreateList(list1,'s');
    CreateList(list1,'d');

     list2 = CreateList(list2,'g');
     CreateList(list2,'e');
     CreateList(list2,'e');
     CreateList(list2,'k');
     CreateList(list2,'s');
     CreateList(list2,'c');

    cout<<"Elements in List 1:-"<<endl;
    display(list1);
    cout<<"\n\nElements in List 2:-"<<endl;
    display(list2);
    cout<<endl;

    cout<<"\n\ncomparison Result of String is ::  "<<comparelistString(list1, list2)<<"\n\n";


    return 0;
}

void display(node *head)
{
    while(head!=NULL)
    {
        cout<<head->data<<" ";
        head=head->next;
    }
}

node *CreateList(node* head, char d)
{
    node *ptr;
    ptr = head;
    if(ptr==NULL)
    {
        ptr = new node;
        ptr->data = d;
        ptr->next = head;
        head= ptr;
    }
    else
    {
        while(head->next!=NULL)
        {
            head= head->next;
        }
        head->next = new node;
        head= head->next;
        head->data =d;
        head->next = NULL;

    }
}

int comparelistString(node *list1, node *list2)
{
    while(list1 !=NULL && list2 !=NULL &&(list1->data == list2->data))
    {
        list1 = list1->next;
        list2 = list2->next;
    }
    if(list1!=NULL && list2!=NULL)
        return((list1->data > list2->data)?1: -1);

    if(list1!=NULL && list2==NULL)
        return 1;
    if (list1==NULL && list2!=NULL)
        return -1;

    return 0;
}

Output

Output
Output


Other Articles:


Other Blogs: Click here

0 comments:

Post a Comment