single linked list

This is a discussion on single linked list within the C Programming forums, part of the General Programming Boards category; If this is a single linked list with a head pointer How can I change the pointer to point to ...

  1. #1
    Max
    Max is offline
    Registered User Max's Avatar
    Join Date
    Jul 2002
    Posts
    110

    single linked list

    If this is a single linked list with a head pointer

    How can I change the pointer to point to Tail?

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #define MAXLINES 50
    #define MAXWORDLENGTH 50
    
    FILE *ifp;
    
    struct word_link
    {
    	char word[MAXWORDLENGTH];
    	struct word_link *pnext;
    };
    
    int main(void)
    {
    	const char ifn[]={"word.txt"};
    	char line[1+MAXLINES];
    	struct word_link *phead,*pthis,*pnew;
    	
    	ifp=fopen(ifn,"r");
    	if (ifp==NULL)
    	{
    		perror(ifn);
    		exit(1);
    	}
    
    	phead=NULL;
    
    	for(;;)
    	{
    		fscanf(ifp,"%s", line);
    		if (feof(ifp)) break;
    		
    		if ((pnew=(struct word_link *)malloc(sizeof(struct word_link)) )==NULL)		
    		{
    			fprintf(stderr,"link1: no storage available\n");
    			exit(1);
    		}
    		
    		strcpy(pnew->word,line);
    				
    		pnew->pnext=phead;
    		phead=pnew;		
    	}
    	
    	for(pthis=phead;pthis!=NULL;pthis=pthis->pnext)
    		printf("%p  %s\n",pthis,pthis->word);
    	
    	free(pnew);
    		
    	fclose(ifp);
    	
        return 0;
    }

  2. #2
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    Get the tail:
    Code:
    if(phead != NULL)
    {
       for(pthis=phead;pthis->pnext != NULL;pthis=pthis->pnext) ;
    }
    Don't forget to free ALL memory

    Code:
    for(pthis=phead; phead != NULL; pthis = phead)
    {
       phead = phead->pnext;
       free(pthis);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unknown memory leak with linked lists...
    By RaDeuX in forum C Programming
    Replies: 6
    Last Post: 12-07-2008, 04:09 AM
  2. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  3. problem with structures and linked list
    By Gkitty in forum C Programming
    Replies: 6
    Last Post: 12-12-2002, 06:40 PM
  4. Template Class for Linked List
    By pecymanski in forum C++ Programming
    Replies: 2
    Last Post: 12-04-2001, 09:07 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 11:21 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21