Below programme doesn’t work for bigger size strings , but it works properly for small strings.I am not sure why sortedInsert function is not taking full length of string.There is no string length constraint also being used in this programme.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/* Link list node */
struct node
{
char* pattern;
struct node* next;
};
/* function to insert a new_node in a list. Note that this
* function expects a pointer to head_ref as this can modify the
* head of the input linked list (similar to push())*/
void sortedInsert(struct node** head_ref, struct node* new_node)
{
struct node* current;
/* Special case for the head end */
if (*head_ref == NULL || (strcmp((*head_ref)->pattern ,new_node->pattern)> 0))
{
new_node->next = *head_ref;
*head_ref = new_node;
}
else
{
/* Locate the node before the point of insertion */
current = *head_ref;
while (current->next!=NULL &&
strcmp(current->next->pattern, new_node->pattern)< 0)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
/* BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert */
/* A utility function to create a new node */
struct node *newNode( char * pattern)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
new_node->pattern = (char *)malloc(sizeof(pattern));
/* put in the data */
strcpy(new_node->pattern , pattern);
new_node->next = NULL;
return new_node;
}
/* Function to print linked list */
void printList(struct node *head)
{
struct node *temp = head;
while(temp != NULL)
{
printf("\n%s", temp->pattern);
temp = temp->next;
}
}
/* Drier program to test count function*/
int main()
{
/* Start with the empty list */
struct node* head = NULL;
struct node* new_node = newNode("a.b.c.d.e.f.g.h.h.j.k.l.m.n.o");
sortedInsert(&head, new_node);
new_node = newNode("a.b.c.de.f.g.h.j.k.l.m.t.y.u.k");
sortedInsert(&head, new_node);
new_node = newNode("a.b.c.d.ef.g.h.h.k.j.l.y.u.l.p");
sortedInsert(&head, new_node);
printf("\n Created Linked List\n");
printList(head);
return 0;
}
Here is the output of above programme, where unexpected output can be seen. Output:
Created Linked List
a.b.c.d.e.f.)
a.b.c.d.ef.g.h.h.k.j.l.y.u.l.p
a.b.c.de.f.g)