Thread: Linked List

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    100

    Linked List

    I'm still trying to insert a node at a passed index in a linked list. This is my function, it doesn't work but i feel like it's close. Any pointers appreciated

    Code:
    void llAddAtIndex(LinkedList** ll, char* value, int index) {
    
      LinkedList* newNode = (LinkedList*)malloc(sizeof(LinkedList));
      newNode->value = value;
      LinkedList* prevNode = *ll;
    
    
      for(int i = 0; i < index; i++){
          prevNode = newNode;
        newNode = newNode->next;
      }
        if (prevNode) {
          prevNode->next = newNode;
          newNode->next = newNode;
        } else { 
            value = *newNode;
            newNode->next = *newNode;
          }
    }

  2. #2
    Registered User
    Join Date
    Feb 2003
    Posts
    596
    Think about what you're doing here:
    Code:
      for(int i = 0; i < index; i++){
         prevNode = newNode;
         newNode = newNode->next;
      }
    Suppose for example that the index value is 10. How useful is it to do
    "prevNode = newNode" 10 times? (Or even once for that matter.)

    And having done that, when will the if condition on the next line
    Code:
      if (prevNode) {
    ever fail?

    Also, there are several special cases that you must consider:
    1. What if ll is an empty list and index is 0?
    2. What if ll is NOT an empty list and index is 0?
    3. What if index is greater than the number of nodes in ll?

  3. #3
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Another linked list problem.......Eternally Confuzzled - Linked List Tutorial
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Declaring linked list inside linked list
    By blueboyz in forum C Programming
    Replies: 33
    Last Post: 04-20-2012, 10:13 AM
  2. Replies: 4
    Last Post: 05-01-2010, 10:19 PM
  3. single linked list to double linked list (help)
    By Countfog in forum C Programming
    Replies: 8
    Last Post: 04-29-2008, 08:04 PM
  4. singly linked list to doubly linked list
    By t48j in forum C Programming
    Replies: 3
    Last Post: 03-23-2005, 06:37 PM
  5. Replies: 6
    Last Post: 03-02-2005, 02:45 AM