-
August 25th, 2013, 06:17 AM
#1
Linked Lists and Pointers
Hi guys, I'm trying to learn how to use Linked Lists. I was wondering if you guys can give me pointers here...
1. Freeing memory allocation - I don't understand the concept of free() that much. I mean, when exactly do I free a node? For example, in the crtNode() function, I used 2 pointers (newNode, curNode). Do I free() them both after I use them in the function?
Knowing that I'll be using those two pointers again in the future (when the user inserts another data). Should I free those two pointers right after they are used in the crtNode()? But they're carrying address information right? If I were to free() them, then they'd lose the data they're carrying, right?
It would be different story with the tmpNode in dspNode(), if I'm not mistaken, since that pointer is only used when the user demands to view the data, so I can free() it after every time the dspNode() finishes displaying all the data in the linked list, right?
Honestly, in the example given to us, the only part that used free() was delNode(). And it freed a temporarily used pointer.
2. In the code below, when I tried using the display option, it only displayed one number. I'm pretty sure there's something wrong with my crtNode() function. Like, if I input 2, 3, 4, only the 2 appears.
Code:
#include<stdio.h>
#include<alloc.h>
struct Node{
int Data;
struct Node *next;
};
struct Node *start;
int menu();
void makNull();
void crtNode(int val){
struct Node *newNode, *curNode;
// Create a new node
newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->Data = val; //save the data to current Data node
newNode->next = NULL; //point the next pointer to NULL
if(start == NULL){
//Re-initialize the start node to point to first node
start = newNode;
curNode = newNode;
} else {
//Set the current node to the newly created node
curNode->next = newNode;
curNode = newNode;
}
}
void dspNode(){
struct Node *tmpNode;
// get the address of the start node
// setting it as the temporary starting node
// for displaying purposes only
tmpNode = start;
while(tmpNode != NULL){
printf("%d\n", tmpNode->Data);
tmpNode = tmpNode->next;
}
getch();
free(tmpNode);
}
int main(){
int opt, val;
start = NULL;
clrscr();
while(1) {
clrscr();
opt = menu();
switch(opt){
case 1:
printf("Enter data: ");
scanf("%d", &val);
crtNode(val);
break;
case 2:
//delete
break;
case 3:
dspNode();
break;
case 4:
exit(0);
default:
break;
}
}
}
int menu(){
int x, opt;
char *m [] = {"Insert", "Delete", "Display", "Exit"};
printf("Linked List Sample\n");
for(x=0; x<=3; x++){
printf("[%d] %s\n", x+1, m[x]);
}
printf("\nChoose option: ");
scanf("%d", &opt);
return(opt);
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|