I'm practicing the implementation of Linked list code. so I write the code:
file LinkedList.c
#include <stdio.h>
#include "function.h"
int main(void) {
//initialize
struct Node myNode = { 10,NULL };
List head = &myNode;
insert(20, head, head);
makeEmpty(head);
return 0;
}
file function.h
//this is the statement of the Linkedlist
#ifndef _FUNCTION_H
#define _FUNCTION_H
struct Node;
//pointer to the strcut Node
typedef struct Node* PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct Node
{
//a struct pointer that point to next struct
int element;
//body
Position Next;
/* data */
};
//清空整张链表
List makeEmpty(List L);
//判断链表是否为空
int isEmpty(List L);
int isLast(Position p, List L);
Position Find(void* x, List L);
void insert(int x, List L, Position P);
#endif /*_function_h*/
file List.c
#include "function.h"
#include <stdio.h>
#include <stdlib.h>
List makeEmpty(List L) {
Position cur = L;
Position next;
while (cur!= NULL) {
next = cur->Next;
free(cur);
cur = next;
}
cur = NULL;
next = NULL;
//这里c是copy by value 所以改变那个指针,如果不赋值的话
//就是用void的话,不会将原来的指针改变。
L = NULL;
return L;
}
//right
int isEmpty(List L) {
return L->Next == NULL;
}
int isLast(Position P, List L) {
//判断P在不在List里
List cur = L;
while (cur->Next != P) {
cur = cur->Next;
}
if (cur == NULL) {
fprintf(stderr, "there is no P in the list L\n");
return -1;
}
if (P->Next == NULL) {
return 1;
}
else {
return 0;
}
return -1;
}
void insert(int x, List L, Position P) {
Position tmpCell;
tmpCell = (Position)malloc(sizeof(struct Node));
if (tmpCell == NULL) {
fprintf(stderr,"out of the space!\n");
}
tmpCell->element = x;
tmpCell->Next = P->Next;
P->Next = tmpCell;
}
but when I run the code , I get the fault that : invalid heap pointer , so why
,and when I write head->Next as the parameter in the function "makeEmpty" ,it can run ,but why, in my program , "head" point to the first struct, so head->Next should point to the second struct. I'm really puzzled.
Your head pointer struct Node myNode = {10, NULL}
is a stack variable and can't be pass to free()
.
One easy solution for that is to create a function to init a new Node:
PtrToNode
create_node(int x)
{
PtrToNode tmp_node;
tmp_node = malloc(sizeof(struct Node));
if (tmp_node == NULL) {
fprintf(stderr,"out of the space!\n");
return NULL;
}
tmp_node->element = x;
tmp_node->Next = NULL;
return tmp_node;
}
After you can init your List with the new node:
int
main(void) {
//initialize
List my_list = NULL;
my_list = create_node(10);
insert(20, my_list , my_list);
makeEmpty(my_list);
return 0;
}