Thread: Singly Linked List - Insert value after given value

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jul 2015
    Posts
    1

    Singly Linked List - Insert value after given value

    I have really been struggling with segmentation faults in my linked lists assignments. I think I do not totally understand the pointers. The assignment below was given to me in its entirety except that I am to create the functions. The functions are insertFront, to add a value to the front of the list (which I have gotten to work), insertBack, to insert a value to the back of the list (which works), isInList, which searches the list for a value input by the user and returns 1 if it is there and 0 if it is not (which works), findNode, which returns the node the value was found in (which mostly works, I need to tweak it), insertAfter, to insert a value after a specified node (which seg faults) and insertBefore, to insert a value before a specified node (which seg faults). I am at my wits end trying to fix these functions. If someone could help me figure out what I am doing wrong and explain it to me in the plainest English possible I would be very, very, grateful!

    Here is the code: (Note insertAfter and insertBefore are done two different ways -- insertBefore with a counter to count the actual node position and insertAfter to check the actual value the next value should be added after -- because I have been trying everything to get them to work. If one way is better than the other, let me know!)

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    struct lnode
    {
      int data;
      struct lnode *next;
    };
    
    
    struct lheader
    {
      struct lnode *start;
      int len;
    };
    
    
    struct lheader *makelist( )
    {
      struct lheader *alist;
      alist = malloc( sizeof( struct lheader ) );
      alist->len = 0;
      alist->start = NULL;
      return alist;
    }
    
    struct lnode *makenode( int val )
    {
      struct lnode *box;
      box = malloc( sizeof( struct lnode ) );
      box->data = val;
      box->next = NULL;
      return box;
    }
    
    
    void insertFront( struct lheader *L, int val )
    {
      struct lnode *newnode;
      newnode = makenode(val);
      newnode->next = L->start;
      L->start = newnode;
    }
    
    
    void insertBack( struct lheader *L, int val, int count )
    {
      struct lnode *trav;
      struct lnode *newnode;
      newnode = makenode(val);
      if ( L->start == NULL )
      {
        L->start = newnode;
      }
     else
     {
       trav = L->start;
       while( trav->next != NULL )
       {
        trav = trav->next;
       }
       trav->next = newnode;
       L->len = count;
     }
    }
    
    
    int isInList( struct lheader *L, int val )
    {
      struct lnode *temp;
      int dupe = 0;
      temp = L->start;
      while ( temp != NULL )
      {
        if ( temp->data == val )
        {
          dupe = 1;
          break;
        }
        else
        {
          temp = temp->next;
        }
      }
      return dupe;
    }
    
    struct lnode *findNode( struct lheader *L, int val )
    {
      struct lnode *ptr;
      struct lnode *check;
      int i = 0;
      ptr = L->start;
      while ( ptr != NULL )
      {
        ++i;
        check->data = i;
        if ( ptr->data == val )
        {
          break;
        }
        else
        {
          ptr = ptr->next;
        }
      }
      return check;
    }
    
    
    void insertAfter( struct lheader *L, struct lnode *p )
    {
      int pos, value;
      struct lnode *nn;
      struct lnode *temp;
      temp = p;
      printf( "What number do you want to insert? " );
      scanf( "%d", &value );
      printf( "Insert after which value: " );
      scanf( "%d", &pos );
      nn = makenode(value);
      if ( L->start == NULL )
      {
        L->start = nn;
      }
      else
      {
        temp = L->start;
        while( temp->next != NULL && temp->data != pos )
        {
          temp = temp->next;
        }
        if ( temp->data == pos )
        {
          nn->next = temp->next;
          temp->next = nn;
          printf("Value is %d: ", nn->data);
        }
        else
        {
          printf( "Value %d not found\n", pos );
        }
      }
    }
    
    
    void insertBefore( struct lheader *L, int val, struct lnode *p )
    {
      struct lnode *newnode;
      struct lnode *temp;
      int pos, i;
      newnode = p;
      printf("Insert before which node? (1-5) ");
      scanf( "%d", &pos );
      if ( L->start == NULL )
      {
        L->start = newnode;
      }
      else
      {
        temp = L->start;
        for( i = 0; i < pos - 1; ++i)
        {
          temp = temp->next;
        }
        newnode->next = temp->next;
        temp->next = newnode;
      }
    }
    
    
    void printlist( struct lnode *front )
    {
      struct lnode *mov;
      mov = front;
      while (mov != NULL)
      {
        printf("%d  ", mov->data);
        mov = mov->next;
      }
      printf("\n");
    }
    
    
    void printer( struct lheader *alist )
    {
      struct lnode *mov;
      printf("--------------------------\n");
      printf("List print, len %d\n", alist->len);
      printlist( alist->start );
      printf("--------------------------\n");
    }
    
    
    int main()
    {
      struct lheader *L;
      struct lnode  *head, *tmp;
      struct lnode  *mark;
      int i, x;
    
      L = makelist();
    
      for (i = 1; i <= 5; ++i)
      {
        x = rand() % 25 + 1;
        printf("-- Adding -- %d\n", x);
        // insertFront( L, x );
        insertBack( L, x, i );
        printer( L );
      }
    
    
      printf(">>>>Value to search: ");
      scanf("%d", &x);
      i = isInList(L, x);
      printf("I is %d\n", i);
      tmp = findNode(L, x);
      if (tmp == NULL)
      {
        printf("NOPE\n");
      }
      else
      {
        printf("Found node %d\n", tmp->data);
      }
      printf(">>>>Value to add: ");
      scanf("%d", &x);
      mark = makenode(x);
      insertBefore( L, x, mark );
      printer( L );
      // insertAfter( L, mark );
      // printer( L );
      return 0;
    }

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Welcome to the forum. Good first post.

    However, you should include instructions on how to trigger the error conditions you're seeing (i.e. what input you are entering, and at what point it goes wrong).



    If you aren't getting warnings, you need to increase the warning level of your compiler.

    Code:
    /*
    main.c||In function 'printer':|
    main.c|187|warning: unused variable 'mov'|
    main.c||In function 'main':|
    main.c|198|warning: unused variable 'head'|
    main.c||In function 'findNode':|
    main.c|107|warning: 'check' is used uninitialized in this function|
    ||=== Build finished: 0 errors, 3 warnings ===|
    */
    The third one is really worth looking into.

  3. #3
    Registered User
    Join Date
    Jun 2015
    Location
    Delhi
    Posts
    35
    You can understand pointers from this:http://www.cs.cf.ac.uk/Dave/C/node10.html - little practice will be enough for clarity.

    If you are new to linked list then please try to break the code into several pieces i.e. a code for linked list with insertion at the front (from left to right), a code for insertion at the back (from right to left) & after these two try ordered (sorted) insertion in linked list - after doing them sequentially and piece wise, things will be much clear (especially after ordered insertion which will clarify almost everything).

    here is code for insertion at the back (right to left) -- it is easier than insertion at front:

    Code:
    #include<stdio.h>#include<stdlib.h>
    struct node{
    int i;
    struct node *link;
    };
    int main()
    {
      struct node *head,*p,*temp;
      int data;
      char c;
      printf("Do you want to enter data? Y/N");
      scanf(" %c",&c);
      if((c=='Y')||(c=='y'))
         {
           head=(struct node*)malloc(sizeof(struct node));
           printf("Enter the data: ");
           scanf(" %d",&data);
           head->i=data;
           head->link=NULL;
         }
      printf("Do you wan to enter more data? Y/N");
      scanf(" %c",&c);
      while((c=='y')||(c=='Y'))
         {
           printf("Enter the data: ");
           scanf(" %d",&data);
           temp=(struct node *)malloc(sizeof(struct node));
           temp->i=data;
           temp->link=head;
           head=temp;
           printf("Do you want to enter more data? Y/N");
           scanf(" %c",&c);
         }
     p=head;
     while(p!=NULL)
         {
           printf("%d ",p->i);
           p=p->link;
         }
    return 0;
    }
    code for insertion at the front (left to right):

    Code:
    #include<stdio.h>#include<stdlib.h>
    struct node{
    int i;
    struct node *next;
    };
    int main()
    {
      struct node *head,*p,*temp;
      int data;
      char c;
      printf("Do you want to enter data? Y/N");
      scanf(" %c",&c);
      if((c=='Y')||(c=='y'))
         {
           head=(struct node*)malloc(sizeof(struct node));
           printf("Enter the data: ");
           scanf(" %d",&data);
           head->i=data;
           head->next=NULL;
         }
      p=head;
      printf("Do you wan to enter more data? Y/N");
      scanf(" %c",&c);
      while((c=='y')||(c=='Y'))
         {
           printf("Enter the data: ");
           scanf(" %d",&data);
           temp=(struct node *)malloc(sizeof(struct node));
           temp->i=data;
           p->next=temp;
           p=temp;
           printf("Do you want to enter more data? Y/N");
           scanf(" %c",&c);
         }
     p=head;
     while(p!=NULL)
         {
           printf("%d ",p->i);
           p=p->next;
         }
    return 0;
    }
    Last edited by smrtshrm; 07-14-2015 at 11:49 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Singly linked list c
    By Creotik in forum C Programming
    Replies: 5
    Last Post: 01-15-2014, 08:42 PM
  2. Need help with Singly Linked List C++
    By luckyali444 in forum C++ Programming
    Replies: 3
    Last Post: 10-18-2011, 11:30 PM
  3. singly linked list
    By Annonymous in forum C Programming
    Replies: 22
    Last Post: 09-10-2011, 05:50 PM
  4. singly linked list
    By right2001 in forum C Programming
    Replies: 3
    Last Post: 08-20-2009, 10:21 AM
  5. Singly Linked List
    By devarishi in forum C Programming
    Replies: 4
    Last Post: 12-24-2008, 12:00 AM

Tags for this Thread