-2
我必須完成此程序。移動指針以便以不同的順序打印
我有這樣的
Name iD Num_of_elements elem(1) elem(2), ... , elem(n)
james 1 3 AAA BBB CCC
arthur 2 2 EEE FFF
james 1 1 KKK
irine 3 4 EEE FFF DDD AAA
james 1 1 XXX
我需要創建一個列表,將文件加載到列表中,並打印責令如下文件:
james 1 3 AAA BBB CCC
james 1 1 XXX
james 1 1 KKK
arthur 2 2 EEE FFF
irine 3 4 EEE FFF DDD AAA
(這是必要的打印之前具有相同iD的人員,然後打印其他人員)。
我已經在ANSI C中創建了程序的一部分,但是我無法按請求完成「最終功能」。
無效printListOrderedByiD(結構清單*頂部) {}
這是我的代碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define len 35
struct elements
{
char name[len];
};
struct list
{
char name[len];
int id;
int numOfElements;
struct elements *pElements; /* pointer to the struct elements */
struct list *next;
};
FILE *openFile(FILE *fp)
{
fp=fopen("file.txt", "r");
if (fp==NULL)
{
perror("");
exit(1);
}
return (fp);
}
struct list *newNode(FILE *fp)
{
int i=0;
struct list *temp=(struct list *)malloc(sizeof(struct list));
fscanf(fp, "%s\t%d\t%d\t", temp->name, &temp->id, &temp->numOfElements);
temp->pElements=(struct elements *)malloc(temp->numOfElements*sizeof(struct elements));
for (i=0; i<temp->numOfElements; i++)
{
fscanf(fp, "%s\t", temp->pElements[i].name);
}
temp->next=NULL;
return temp;
}
struct list *insertAsLast(struct list *top, FILE *fp) /* this function will insert every node at the end of the list */
{
if (top==NULL)
{
top=newNode(fp);
}
else
{
top->next=insertAsLast(top->next, fp);
}
return top;
}
void printList(struct list *top) /* this procedure will stamp the list as loades from the file */
{
int i=0;
if (top==NULL)
{
printf("//\n");
}
else
{
printf("%s %d %d ", top->name, top->id, top->numOfElements);
for (i=0; i<top->numOfElements; i++)
{
printf("%s ", top->pElements[i].name);
}
printf("\n");
printList(top->next);
}
}
int main()
{
struct list *top=NULL;
char firstLine[200];
FILE *fp=NULL;
fp=openFile(fp);
fgets(firstLine, 200, fp); /* in order to jump the 1st line */
while (!feof(fp))
{
top=insertAsLast(top, fp);
}
fclose (fp);
printList(top);
return 0;
}
任何人能幫助我嗎?
請你能解釋一下什麼是
static int cmp(const void *a, const void *b){ int x = (*(struct list**)a)->id; int y = (*(struct list**)b)->id; return x < y ? -1 : x > y; }
謝謝 – 2014-08-30 14:47:48數組的元素@Mariadegregorio傳遞一個指向元素作爲在'qsort'使用'無效*'來比較函數。因此'(struct list **)a'是'const void * a' - >'struct list **','*'是'struct list **' - >'struct list *'。 – BLUEPIXY 2014-08-30 14:57:06
@如果第一個參數被認爲分別小於,等於, 或大於第二個參數,則Mmaldegregorio比較函數應該返回一個小於,等於或大於零的整數。 – BLUEPIXY 2014-08-30 15:00:12