0

Doing my CS homework, but have no idea how to write the pseudocode.

Let insert(L,n)insert blablabla

2 Answers2

0

It would be easy to implement a recursive solution. The code in c++ as following.

struct Node {
    int val;
    Node *next;
    Node(int t): val(t), next(nullltr) 
};
//return the node after inserting n.
Node* insert(Node *L, int n) {
   if (L == nullptr) return new Node(n);
   if (L->val < n) {
       L->next = insert(L->next, n);
   } else if (L->val > n) {
       Node *tmp = new Node(n); 
       tmp->next = L;
       L = tmp;
   }
   //do nothing when L->val == n.
   return L;
}
notbad
  • 2,797
  • 3
  • 23
  • 34
0

If no duplicates are allowed you can assume the list is looking something like this

...5,6,7,8...

Using that knowledge, you know you need to step a maximum of n steps to reach the destination. You can do this via recursion or looping through.

Recursion(Node e,int n):

  1. If e.value is n return.
  2. If e.next is not NULL, call Recursion(e.next, n) else e.next = new node consisting of n.
  3. Finish.

Iterative-way(int n):

  1. node = list.root
  2. Loop while node is not null:
  3. If node.value is n, stop.
  4. End loop
  5. If node.next is NULL, node.next = new node consisting of n. else (new node consisting of n).next = node.next and node.next = new node consisting of n.
Muli Yulzary
  • 2,559
  • 3
  • 21
  • 39