GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 07-Nov-2007, 01:59
Peter_APIIT Peter_APIIT is offline
Regular Member
 
Join Date: May 2007
Location: Malaysia
Posts: 479
Peter_APIIT can only hope to improve
Thumbs up

Link List In C


Hello respective expert programmer,

i truly a noob in programming.

I have create a program that use linked list data structures but haven't successful.

Basically, my idea is like this, let the user choose from the menu and insert linked what ever they like until they have satisfied.After that, choose again from the menu to display the list or to something else but i think my list has scope problem where in display the list become NULL again.

My malloc memory allocation is done at insert function and display function is in another function. Therefore, the list become NULL in display.

How to solve this problem ? I try to use global variable in some cases.

Please help me to solve this problem.


Below is my program:
CPP / C++ / C Code:
#include<stdio.h>
#include<stdlib.h>
#include "Link_List.h"

/*
   1. Insert Behind
   2. Insert In Front
   3. Random Insert -nth
   4. Remove Behind until zero or one only 
   5. Remove In Front
   6. Random Remove -nth
   7. Display 
*/

// Global variable for head and tail
  struct node *head, *tail, *traversal;
  struct node *list;

// ----------------------------------------------------
void InsertBehind(struct node *);


void Display(struct node *);

// -----------------------------------------------------
int main(int argc, char *argv[])
{
	int choice;

	head = malloc(sizeof(struct node));
	tail = malloc(sizeof(struct node));
	traversal = malloc(sizeof(struct node));

	head = list;
	
	do
	{
		system("cls");
		printf("\n\n\n\n\t\t\t\t   Main Menu\n\n\t\t\t\t1. Insert Behind\n\t\t\t\t2. Insert In Front\n\t\t\t\t3. Random Insert\n");
		printf("\t\t\t\t4. Remove Behind\n\t\t\t\t5. Remove In Front\n\t\t\t\t6. Random Remove\n\t\t\t\t7. Display\n");
		printf("\n\n\t\t\tPlease Enter a valid choice from 1 to 7");
		printf("\n\n\t\t\t\t\tChoice: ");
		scanf("%d", &choice);

		switch (choice)
		{
		case 1:
			InsertBehind(list);
			break;
		case 7:
			Display(list);
			break;
		default:
			printf("Invalid Choice");
			break;
		}
	}while(1);
	

	// To avoid memory leak 
	free(head);
	free(tail);
	free(traversal);
	free(list);

	
	return 0;
}
// ------------------------------------------------------
void InsertBehind(struct node *list)
{
	list = malloc(sizeof(struct node));

	if (list != NULL)
	{
		system("cls");
		printf("Enter a value into the Linked List : ");
		scanf("%d", &list->value);
//		printf("%d", list->value);

        // If head not pointed to first node 
        // then head pointed to first node
        // else tail pointed to second node
		if (head != list)
		{
			head = list;
		}
		else
		{
			list->next = list;
			tail = list->next;
			
			if (tail->value == 500)
			{
				traversal = head;

				while(traversal != NULL)
				{
					printf("The value of List is ", traversal->value);
					traversal = list->next;
				}
			}
		}
	}
	else
	{
		printf("Heap Memory not enough");
	}
}
// ------------------------------------------------------
void Display(struct node *list)
{
	traversal = head;

	while(traversal != NULL)
	{
		printf("The value of List is ", traversal->value);
		traversal = list->next;
	}
}

Header File:

#ifndef Link_List
#define Link_List

struct node
{
	int value;
	struct node *next;
};

#endif

Thanks for your help.

EDIT:

What wrong with this code ?

CPP / C++ / C Code:
	for (loop=0;loop<3;++loop)
	{
		list = malloc(sizeof(struct node));
		if (list != NULL)
		{
			if (head != list)
			{
				head = list;
				tail = list;
				traversal = list;
				list->value = value;
			}
			else
			{
				list->value = ++value;
				list->next = list;
				tail = list->next;
			}
		}
	}

	do 
	{
		printf("The value is %d \n", traversal->value);
		traversal = traversal->next;
	}while (traversal != NULL);

Your help is greatly appreciated by me and others.
Last edited by LuciWiz : 07-Nov-2007 at 04:09. Reason: Please insert your C++ code between [cpp] & [/cpp] tags
  #2  
Old 07-Nov-2007, 02:35
Peter_APIIT Peter_APIIT is offline
Regular Member
 
Join Date: May 2007
Location: Malaysia
Posts: 479
Peter_APIIT can only hope to improve

Re: Link List In C


The edit section is all in main.

Thanks.
  #3  
Old 07-Nov-2007, 03:05
ahbi82 ahbi82 is offline
Member
 
Join Date: Jul 2006
Posts: 114
ahbi82 will become famous soon enough

Re: Link List In C


One of the biggest problem i can see is the pointer "head" is floating.

u malloc "head" in the beginnint which gives you an address to a memory location.

CPP / C++ / C Code:
head = malloc(sizeof(struct node));

You THE assign it to point to another address which the global pointer "list" is pointing.

CPP / C++ / C Code:
head = list;

AND inside your function

CPP / C++ / C Code:
void InsertBehind(struct node *list)
{
     list = malloc(sizeof(struct node));

    ..............
    ..............
}

list is already your argument for your list!!!!!!! Why are you assigning it to another memory location.




I'll try and work a simple Linked List and post in a later post.

Hope this helps!!
  #4  
Old 07-Nov-2007, 07:48
fakepoo fakepoo is offline
Regular Member
 
Join Date: Oct 2007
Posts: 509
fakepoo is a jewel in the roughfakepoo is a jewel in the roughfakepoo is a jewel in the rough

Re: Link List In C


One more thing that you may think about changing is that you have your linked-list code embedded with your input/output statements. This is very bad for creating reusable code which, especially with a linked list, should be a goal. This way you could put the same linked list into a GUI program or a non-DOS command line.
  #5  
Old 07-Nov-2007, 15:41
fakepoo fakepoo is offline
Regular Member
 
Join Date: Oct 2007
Posts: 509
fakepoo is a jewel in the roughfakepoo is a jewel in the roughfakepoo is a jewel in the rough

Re: Link List In C


Here's a good start for you:

CPP / C++ / C Code:
// Link_List.h

struct node
{ int value;
  struct node * next;
};

struct Link_List
{ struct node *Head;
};

void LL_Initialize( struct Link_List *List );
void LL_Append( struct Link_List *List, int value ); 
int  LL_GetAt( struct Link_List *List, int index );
// other necessary functions
CPP / C++ / C Code:
// Link_List.cpp

#include "Link_List.h"

void LL_Initialize( struct Link_List *List )
{ List->Head = NULL;
}

void LL_Append( struct Link_List *List, int value )
{ // create the new node and initialize it's members
  struct node *newNode = malloc(sizeof(struct node));
  newNode->value = value;
  newNode->next = NULL;
  
  struct node *n = List->Head;
  if(n == NULL) List->Head = newNode;
  else
  { while(n->next != NULL) n = n->next;
    n->next = newNode;
  }
}

int LL_GetAt( struct Link_List *List, int index )
{ struct node *n;

  for(i=0,n=List->Head;n != NULL;n=n->next,i++)
  { if(i == index) return n->value;
  }
  return -1; //or some other error value
}

// Finish the other function implementations
This way, you can add this file to any program and you won't have to do anything to the file.
CPP / C++ / C Code:
// main.cpp

#include "Link_List.h"

int main()
{ struct Link_List myList;
  int myInt;

  // Initialize the list
  LL_Initialize(&myList);

  // Get user input
  printf("Enter a value into the Linked List : ");
  scanf("%d", &myInt);

  // Append it to the list
  LL_Append(&myList, myInt);

  //.....
  //.....

  LL_Free( &myList );
}
  #6  
Old 07-Nov-2007, 20:57
Peter_APIIT Peter_APIIT is offline
Regular Member
 
Join Date: May 2007
Location: Malaysia
Posts: 479
Peter_APIIT can only hope to improve

Re: Link List In C


I wonder why you create another struct called Link_list.

I create the first list called list and second also called list. This is my purpose.

How about my first program ?

The head is dangling but i have point it to first list in the next few statement.

Why it is still NULL ?

Thanks for your help.
  #7  
Old 08-Nov-2007, 07:26
fakepoo fakepoo is offline
Regular Member
 
Join Date: Oct 2007
Posts: 509
fakepoo is a jewel in the roughfakepoo is a jewel in the roughfakepoo is a jewel in the rough

Re: Link List In C


The reason for the second struct is for future functionality. If I were to extend this to be a doubly-linked list, my Link_List structure would also contain a Tail member.

I don't know what your code is trying to do in InsertBehind(), but if you pass a node * to it, then you should not malloc() within it. Did you see the way that I implemented LL_Append()? That should give you a little help on how you should implement InsertBehind(). Have you separated your linked list logic from the I/O yet? Go ahead and post your most recent code.
  #8  
Old 15-Jan-2008, 20:01
Peter_APIIT Peter_APIIT is offline
Regular Member
 
Join Date: May 2007
Location: Malaysia
Posts: 479
Peter_APIIT can only hope to improve

Re: Link List In C


As far as i know, the struct node to represent a single node and struc linked list is to represent a whole linked list.

Am i correct ?

The head pointer inside struct LList is pointing to first node.

Thanks for your help.
  #9  
Old 16-Jan-2008, 01:34
Peter_APIIT Peter_APIIT is offline
Regular Member
 
Join Date: May 2007
Location: Malaysia
Posts: 479
Peter_APIIT can only hope to improve

Re: Link List In C


Before this, i study myself, my semester has started few weeks ago for data structures.

CPP / C++ / C Code:
#ifndef _LList_
#define _LList_

struct node
{
	int value;
	struct node *next;
};


	
// Add index to struct

#endif


CPP / C++ / C Code:
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

#include "Linked_List.h"

// -------------------------------------------------------
/*
   1. Insert Behind
   2. Insert In Front
   3. Random Insert -nth 
   4. Remove Behind until zero or one only 
   5. Remove In Front
   6. Random Remove -nth
   7. Display 
*/

 /* 
	Random must have a index to indicate the postion where
    almost same as array in order to achieve fast 
	processing
*/


// -------------------------------------------------------

// tail->next = head->next; Circular Link List

void draw();

void Initialize(struct node *);
int queryNode();
void check(struct node **);

void InsertBehind(struct node **, int);

struct node *head;


// ------------------------------------------------------
int main(int argc, char *argv[]) // char **argv
{
// 	struct node **currentNode;

	typedef struct node ** multiNode;
	multiNode dynamicNode;
	
	int numberNode, loop;

	draw();
	numberNode = queryNode();
	
	dynamicNode = malloc(sizeof(struct node *) * numberNode);
	assert(dynamicNode != 0);
	check(dynamicNode);

/*	for (loop=0;loop<numberNode;++loop)
	{
		printf("%d\n", dynamicNode[loop]->value);
		dynamicNode[loop]->next = NULL;
	}
*/	
	

	InsertBehind(dynamicNode, numberNode);
	


	return 0;
}

// ------------------------------------------------------
void draw()
{
	int loop;

	printf("\n\n\n\t\t");

	for (loop=0;loop<60;++loop)
	{
		printf("-");
	}
	
	printf("\n\n\t\t\t  Welcome to newly Link List Simulation Program");
	printf("\n\n\n\t\t");
	for (loop=0;loop<60;++loop)
	{
		printf("-");
	}
	printf("\n\n\n\n");
	
}
// -------------------------------------------------------
void Initialize(struct node *head)
{
	head->value = 0;
	head->next = NULL;
}
// -------------------------------------------------------
int queryNode()
{
	int numberNode;

	printf("\n\n\t\t\tHow many node in the Link List : ");
	scanf("%d", &numberNode);

	return numberNode;
}
// -------------------------------------------------------
void check(struct node ** dynamicNode)
{
	if (dynamicNode == 0)
	{
		printf("Memory exhausted");
		exit(0);
	}
}
// ------------------------------------------------------
void InsertBehind(struct node ** dynamicNode, int numberNode)
{
	int loop, value;
	// 	int number[]; *(number + loop)

	int *array;

	printf("\n\n");
	if (head == NULL)
	{
		(struct node **)head = dynamicNode;
		for (loop=0;loop<numberNode;++loop)
		{
			printf("\t\t\tEnter a value store to Link List : ");
			scanf("%d", &value);
			
			array = malloc(sizeof(int) * numberNode);
			assert(array!= 0);
			if (array == 0)
			{
				printf("Memory exhausted");
				exit(0);
			}

			*(array + loop) = value;

			

		
		// *(array + loop);
			printf("%d\n", dynamicNode[loop]->value);
//			currentNode[loop]->next = NULL;
		
		}
	}	
}


I cannot debug this program. As far as i know, char ** is same as char *[] but char *[] is limited to constant solution.

I ask user to enter number of node and malloc it by
dynamicNode = malloc(sizeof(struct node *) * numberNode);

I don't know whether i correct or not.

Please help me.

Thanks for your help.
  #10  
Old 16-Jan-2008, 07:27
seprich seprich is offline
Member
 
Join Date: Jun 2007
Posts: 110
seprich has a spectacular aura aboutseprich has a spectacular aura about

Re: Link List In C


Quote:
Originally Posted by Peter_APIIT

I cannot debug this program. As far as i know, char ** is same as char *[] but char *[] is limited to constant solution.
How did you try to debug your program ?
For one thing your program does not compile.
I tried to compile (me using gcc) and got :
test.c: In function ‘InsertBehind’:
test.c:134: error: invalid lvalue in assignment
(line number not same as in your posting)
This refers to:
CPP / C++ / C Code:
(struct node **)head = dynamicNode;
which is mangled. Type cast before the "head" is pointless.

The problem is that head is (struct node *) type and dynamicNode is (struct node **)
Solutions are many:
1. maybe you should change the type of "type"
2. maybe you should change the type of "dynamicNode"
3. maybe you could write something like "type = *(dynamicNode+offset);"
4. most likely re-arrange logic and datatypes in many places.

Everything depends on what each and every variable exists for in the first place.
e.g. What kind of creature is dynamicNode supposed to be ?


Quote:
Originally Posted by Peter_APIIT
I ask user to enter number of node and malloc it by
dynamicNode = malloc(sizeof(struct node *) * numberNode);

Notice that you just allocated memory for specific amount of pointers.
Each pointer will still be undefined.. !!
But then again normal memory management concept of linked lists do not allocate memory this way.
What is it that you try to do ?
 
 

Recent GIDBlogDeveloping GUIs with wxPython (Part 2) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
game problem using linkedListType.h and random function eureka360 C++ Forum 5 16-Feb-2007 10:48
C++ class -- Please help vnca_1 C++ Forum 3 14-Jun-2006 12:31
[Include] Doubly-linked List dsmith C Programming Language 6 14-Apr-2006 13:12
linked list error message Krandygrl00 C++ Forum 4 22-Jun-2005 14:13

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 06:43.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.