Doing my CS homework, but have no idea how to write the pseudocode.
Let insert(L,n)insert blablabla
Doing my CS homework, but have no idea how to write the pseudocode.
Let insert(L,n)insert blablabla
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;
}
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):
Iterative-way(int n):