Hello teddy78,
See the program listed at the end of the answer. With the following
input file (id.txt)
Teddy Karthig w0117445
Compiled the source file on a Unix system using
cc -o id -g id.c
and run with
./id id.txt
to produce
head->0->1->1->7->4->4->5
sorted->7->5->4->4->1->1->0
which displays the list as entered and the new sorted list.
You may need to make changes to meet your specific needs - the
instructions are still a little unclear. There are a couple printf
calls commented out - enable them if you want to see the program run
as well. If you need help - request a clarification. Good luck.
--Maniac
id.c follows...
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct l;
struct l {
struct l *next;
char c;};
int main (int argc,
char *argv[],
char *envp[])
{
FILE *idfile;
const int maxstr = 20;
char first[maxstr], last[maxstr];
char id[maxstr];
struct l *n = NULL;
struct l *head = n;
struct l *r, *s, *t;
struct l *sorted = n;
int i;
idfile = fopen(argv[1], "r");
if (idfile == NULL) {
printf("%s: Failed to open input\n", argv[0]);
perror(argv[0]);
return 1;
}
if ((i=fscanf(idfile, "%s %s %s", first, last, id)) < 3) {
printf("%s: Failed input at %d, quitting\n", argv[0], i);
perror(argv[0]);
return 1;
}
/* this code creates the list in order */
s = n; /* no tail yet */
for (i=0; i<strlen(id); i++) {
if (isdigit(id[i])) {
t = malloc (sizeof(struct l));
t -> c = id[i];
t -> next = n;
if (head==n) {
head = t;
}
else {
s->next = t;
}
s = t;
/* printf("%d %x %x %x %c\n", i, head, t, s, t->c); */
}
}
/* print out in order to show done OK */
printf("head");
for (s=head; s!=n; s=s->next) {
printf("->%c", s->c);
}
printf("\n");
/* sort the list (insertion) */
sorted = head;
head = head->next;
sorted->next = n; /* first item removed */
for (s=head ; head!=n; s=head) {
head = head->next; /* remove it */
if (sorted->c<=s->c) { /* insert at head */
s->next = sorted;
sorted = s;
/* printf("Insert %c at head before %c\n", sorted->c,
sorted->next->c); */
}
else { /* find proper spot */
r = sorted;
for (t=sorted->next; t!=n; t=t->next) {
if (t->c<=s->c) { /* insert here */
s->next = t;
r->next = s;
/* printf("Insert %c before %c\n", t->c, s->c); */
break;
}
else
r = r->next;
}
}
}
/* print the sorted output */
printf("sorted");
for (s=sorted; s!=n; s=s->next) {
printf("->%c", s->c);
}
printf("\n");
return 0;
} |