#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    101
    Rep Power
    0

    Ok. What am I doing wrong now?!? (another linked list problem)


    First of all, I know I did many posts on this topic in the past. I just want to say thank you all C programmers for helping me. I'm not giving up on this. I want to understand this.

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    typedef struct num {
    	int val;
    	struct num *next;
    } num;
    
    num *createList(int info)
    {
    	num *head = NULL;
    	num *temp = (num *)malloc(sizeof(num));
    	temp->val = info;
    	temp->next = head;
    	head = temp;
    	return head;
    }
    
    void Insert(num *head,int value)
    {
    	num *temp1 = (num *)malloc(sizeof(num));
    	num *temp = (num *)malloc(sizeof(num));
    	temp1 = head;
    	while(temp1->next != NULL)
    	{
    		temp1 = temp1->next;
    	}
    	temp->val = value;
    	temp->next = NULL;
    	temp1->next = temp;
    }
    
    int main()
    {
    	num *iterate;
    	num *one = createList(1);
    	Insert(one,3);
    	Insert(one,6);
    	Insert(one,10);
    	for(iterate = one->next;iterate != NULL;iterate = iterate ->next)
    	{
    		printf("%d\n",one->val);
    	}
    	getchar();
    	return 0;
    }
    When I run this, all it prints is 3 one's. Why?

    http://www.codeproject.com/Articles/24684/How-to-create-Linked-list-using-C-C

    That's the website I used for a tutorial. I liked it but it was in C++ code so I just converted it to C code. I did everything it asked (just for the insertation part) but my code still doesn't go correctly. Can someone please explain why?

    I'm thinking it has to do with the Insert function I created (edited), where I assign the values but don't do anything to them afterwards. I just don't know how to fix this.
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,367
    Rep Power
    1870
    > printf("%d\n",one->val);
    But iterate is your loop variable.

    > for(iterate = one->next;iterate != NULL;iterate = iterate ->next)
    You should probably start at one, not one->next.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo