0

I want to insert at the beginning of the root of this function:

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

typedef struct elem Node;


void shiftInsert(Node *n, int v){
    int tmp;
    while (n != NULL){      


       n = n->next;
   }
}  

When the Node *n is: 1 -> 2 -> 3 -> 4 -> 5 and call shiftInsert(88)
the output of Node *n needs to be:

88->1 -> 2 -> 3 -> 4
how can I achieve this?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Dirk
  • 3,095
  • 4
  • 19
  • 37

1 Answers1

2

It looks like shiftInsert is designed to insert a value at the beginning of the linked list, and then push the first node's (former) value to the next node, repeating until the last value has been "shifted" off. I would try something like:

void shiftInsert(Node *n, int v) {

  Node *iterator = n;
  int tmpPrev = v;
  int tmpCurr = 0;

  while(iterator != NULL) {
    //save the current value
    tmpCurr = iterator->value;
    //set the new value
    iterator->value = tmpPrev;
    //save the old value
    tmpPrev = tmpCurr;
    //next node
    iterator = iterator->next;
  }
}

Demo

Nick Reed
  • 4,989
  • 4
  • 17
  • 37
  • Well, `v` needs to be the value of `n->value` and everything needs to shift to the right and the last value needs to be removed. So removing last element of `n` and adding `v` as first element like this: `1 -> 2 -> 3 -> 4 -> 5` becomes `88->1 -> 2 -> 3 -> 4` when `v` is `88` – Dirk Oct 29 '19 at 12:28
  • Ah, I was overcomplicating it. See edited answer. – Nick Reed Oct 29 '19 at 12:32
  • Well, now the output is `88 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 10 -> NULL` which needs to be `88 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL` – Dirk Oct 29 '19 at 12:37
  • Off-by-one error! See final updated answer, and [demo](https://repl.it/repls/FaintNavajowhiteStrings). – Nick Reed Oct 29 '19 at 12:39