我的输入文件是
1
2
3
4
5
我的输出应该看起来像
1 -> NULL
2 -> 1 -> NULL
3 -> 2 -> 1 -> NULL
4 -> 3 -> 2 -> 1 -> NULL
5 -> 2 -> 3 -> 2 -> 1 -> NULL
这是我的功能
void printList(Node* first)
{
Node *temp;
temp=first;
printf("elements in linked list are\n");
while(temp!=NULL)
{
printf("%d -> NULL\n",temp->value);
temp=temp->next;
}
}
这是完整的程序
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int value;
struct node* next;
}Node;
Node* createNode(int data);
Node* insertFront(Node* first, Node* newNode);
void printList(Node* first);
void deleteList(Node* first);
int main(int argc, const char **argv)
{
int numItems, ch;
FILE *fp;
numItems = 0;
fp = fopen(argv[1], "r");
if(fp == NULL)
{
fclose(fp);
return -1;
}
while ((ch = getc(fp)) != EOF)
{
if (ch = '\n') numItems++;
}
fclose(fp);
Node *first = NULL;
Node *newNode;
Node *Next;
int i;
for(i = 1; i <= numItems; i++)
{
newNode = createNode(i);
first = insertFront(first, newNode);
}
printList(first);
deleteList(first);
return 1;
}
Node* createNode(int data)
{
Node *newNode;
newNode = malloc(sizeof(Node));
newNode -> value = data;
newNode -> next = NULL;
return newNode;
}
Node* insertFront(Node* first, Node* newNode)
{
if (newNode == NULL) {
/* handle oom */
}
newNode->next=NULL;
if (first == NULL) {
first = newNode;
}
else {
Node *temp=first;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next=newNode;
first = newNode;
}
return first;
}
void printList(Node* first)
{
Node *temp;
temp=first;
printf("elements in linked list are\n");
while(temp!=NULL)
{
printf("%d -> NULL\n",temp->value);
temp=temp->next;
}
}
void deleteList(Node* first)
{
Node *temp;
temp=first;
first=first->next;
temp->next=NULL;
free(temp);
}
谁能指出我正确的方向,我在这里骑着链表斗争巴士。提前致谢。