#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;
fp = fopen(argv[1], "r");
while ((ch = getc(fp)) != EOF)
{
if (ch = '
') 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
");
while(temp!=NULL)
{
printf("%d
",temp->value);
temp=temp->next;
}
}
void deleteList(Node* first)
{
Node *temp;
temp=first;
first=first->next;
temp->next=NULL;
free(temp);
}
Tried running with gdb and this is what I got, first real experience trying to make a linked list.
Program received signal SIGSEGV, Segmentation fault.
_IO_getc (fp=0x0) at getc.c:40
40 _IO_acquire_lock (fp);
I'm not sure what I'm doing wrong here? Thanks for any tips in advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…