C Insert Element Into List At Given Index - c

I have a programming question in C where I am trying to design a List and add an element at a given index.
Here is my insertElement method:
ListElement* getNextElement(ListElement *listElement){
return listElement->nextElement;
}
/* Insert a given element at the specified index in a specified list. Shifts
* all other elements to the right, increasing their index by 1.
* Requires 0 <= index <= listSize(), otherwise the element should not be inserted.
*/
void insertElement(List *list, ListElement *listElement, int index) {
ListElement* tempElement = list->headElement;
int count = 0;
while (tempElement != NULL) {
if (count == index) {
}
tempElement = getNextElement(tempElement);
count++;
}
}
But I don't actually know how to shift over and insert the element.
Here is how I attempt to insert:
int main() {
ListElement* newElement = malloc(sizeof(ListElement));
insertElement(&myList, newElement, 1);
exit(EXIT_SUCCESS);
}
Can anybody help me out? Thanks in advance.

The beauty of a linked list is that, unlike an array, you don't need to shift or move anything in order to do an insert.
Assume your list is A->C and you want to insert B after A to give A->B->C.
A->nextElement is set to C; that needs to change.
B->nextElement is not set; that needs to change.
You should be able to see how to accomplish that with what you're given.

Related

How can i generate a binary code table of a huffman tree?

I want to implement an function which gives me a binary code for each char in a huffman tree.
To implement the function i tried traversing the table by using a recursive function. However i don't know how to fill the result the binary code for each char so that the function returns an array of struct with all the chars and binary codes
I hope someone can point me in the right direction.
Thanks ahead!
Ok, let's see a possible solution:
#include <stdint.h>
typedef struct code {
size_t code_length;
uint32_t code;
} code;
void compute_code_table(tree_t node, code *t, code c)
{
if (node->left == NULL)
t[node->letter] = c;
else {
c.code_length++;
c.code <<= 1;
compute_code_table(node->left, t, c);
c.code += 1;
compute_code_table(node->right, t, c);
}
}
void code_print(code *c)
{
size_t n = c->code_length;
while (n --> 0)
putchar('0' + ((c->code >> n) & 1));
}
int main(void)
{
tree_t root = fixed_tree();
code table[256] = { 0 };
code c = { 0 };
compute_code_table(root, table, c);
for (size_t i = 0; i < 256; ++i) {
if (table[i].code_length) {
printf("%c\t", i);
code_print(table + i);
printf("\n");
}
}
}
Basically the idea is to have a table which is filled at every leaf. While doing the recursion we pass the current node, the table and the current code. If we are at a leaf we just store the code in the table, otherwise we need to perform the recursion: increase the code length, add a 0 in the least significant bit and do the left branch, then change that 0 to a 1 and do the right branch.
I would start by making compute_code_table recursive, this allows you to easily traverse the tree.
Secondly, it helps for every task or assignment to search online for some sources which explain (in pseudo-code or not) how to do your specific task. In this case, this yields the following explanation:
To generate a huffman code you traverse the tree to the value you
want, outputing a 0 every time you take a lefthand branch, and a 1
every time you take a righthand branch. (normally you traverse the
tree backwards from the code you want and build the binary huffman
encoding string backwards as well, since the first bit must start from
the top).
siggraph.org
In C, this could be implemented as such:
int compute_code_table_for_node(tree_t tree, node_t target_node, node_t current_node, int code_table) {
// Check for target
if ( current_node == target_node ) {
// Found target
return code_table;
}
// Check if end-node
if ( current_node->left == NULL && current_node->right == NULL ) {
// Is an end node
return -1;
}
// Try left
int left = compute_code_table_for_node(tree, target_node, current_node->left, code_table << 1 + 0);
// Try right
int right = compute_code_table_for_node(tree, target_node, current_node->right, code_table << 1 + 1);
// Find which path was taken
if ( left == -1 ) {
// Left path didn't find it, so it must be the right path:
return code_table << 1 + 1;
} else {
// Left path found it
return code_table << 1 + 0;
}
}
Then you only have to call compute_code_table_for_node(tree, node, tree->head, 0) for every node in the tree.
This piece of code won't work for your specific case, so you will have to rewrite it.

bitwise right shift affecting another short

I am using bitwise operators to shift the binary value of shorts within a linked list. The function is recursive and after an arbitrary number of occurrences, my right shift seems to affect the value of a short in the next link despite me not pointing to this link at all at this point of the function. Here is my code :
static void move_right(t_tetri *piece) {
int i;
i = 0;
piece->x_offset++;
while (i < piece->height) {
piece->shape[i] = piece->shape[i] >> 1;
i++;
}
}
int ft_solve(t_map *map, t_tetri *list) {
if (list == NULL) return (1);
while (list->y_offset + list->height <= map->size) {
while (list->x_offset + list->width <= map->size) {
if (put_tetri(map, list)) {
set_piece(map, list);
if (ft_solve(map, list->next)) return (1);
else unset_piece(map, list);
}
move_right(list);
}
reset_piece(list);
}
list->y_offset = 0;
return (0);
}
piece->shape is an array containing 4 short but I'm mostly concerned about the first of these here. In certain cases (not all) when I go through the move_right function the value of piece->next->shape[0] is shifted in the same way, which poses a big problem for the next recursion of ft_solve.
Would anyone have any idea?
I can post more of my code if necessary, I'm not really used to ask questions here so if you need more information I'm ready to add it.

Doubly Linked List C, insertion at specific position

I could really use some help with an address book program I've been struggling on for days now. I'm working with a doubly linked list in C. I'm trying to add nodes into the list at user-entered positions, starting with position 0. The positions will not be entered out of range. (no inserts at position 1 before something at position 0 etc.) The positions can be repeated though: inserting the new node in the position before the previous position occupant. (for example: if position 1 has x, and new node is inserted at position 1 with y, position 1 now has y and position 2 has x)
I need to take the user entered position number and retrieve the current person in that position, but I can't quite get it right. Also, I have included my insert function if you wanted to take a look at that as well because it isn't working properly either. Thanks for any help!
EDIT: The main problem right now is that my code for finding pPersonCur is failing when position == 1. Also, the insert function is not entering things in the proper order (the newest insertion in a position does not displace the older insertion correctly). The broken pPersonCur code makes it hard to diagnose why exactly this is, however.
addressbook.h excerpt:
typedef struct person Person;
struct person {
char lastName[255];
char firstName[255];
char email[255];
char phoneNumber[255];
Person *pNext;
Person *pPrev;
};
addressbook.c excerpt:
#include "addressbook.h"
Person * InsertPerson(Person * pPersonCur) {
Person * pPersonNew;
/* data gathered for CreatePerson() function here */
pPersonNew = CreatePerson(pLastName, pFirstName, pEmail, pPhoneNumber);
if (pPersonCur)
{
pPersonNew->pNext = pPersonCur;
pPersonNew->pPrev = pPersonCur->pPrev;
pPersonCur->pPrev = pPersonNew;
if (pPersonNew->pPrev)
pPersonNew->pPrev->pNext = pPersonNew;
} else
{
pPersonNew->pPrev = pFirst;
pPersonNew->pNext = NULL;
if (pFirst)
pFirst->pNext = pPersonNew;
}
return (pPersonNew);
}
main.c excerpt:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "addressbook.h"
Person *pFirst; /* First name in list */
int main(void) {
Person *pPersonCur = NULL; /* current Person */
int bDone = 0, position = 0, counter = 0;
pFirst = NULL;
printf("Ready\n");
while (!bDone) {
char input = getchar();
switch (input) {
case 'a':
counter = 0;
scanf("%d", &position); /* Where desired position is entered */
if (position == 0) {
if (pFirst) {
if (pFirst->pNext) {
pPersonCur = pFirst->pNext;
}
} else {
pPersonCur = pFirst;
}
} else {
pPersonCur = pFirst->pNext;
while (counter < position) {
pPersonCur = pPersonCur->pNext;
counter++;
}
}
InsertPerson(pPersonCur); /* Takes in person at desired position, return value is new inserted person */
break;
/* Some other cases here */
case 'q':
bDone = 1;
break;
}
}
/* Rest of code */
It seems so that you never assign a value to pFirst.
When position is not 0 the line pPersonCur = pFirst->pNext; is executed and pFirst in this place is still NULL.
Add a condition to your insert function to check whether list's head is assigned.
Person * InsertPerson(Person * pPersonCur) {
. . .
else
{
pPersonNew->pPrev = pFirst;
pPersonNew->pNext = NULL;
if (pFirst)
pFirst->pNext = pPersonNew;
else
pFirst = pPersonNew; // If pFirst is not assigned, assign it to newly created person
}
return (pPersonNew);
}
Despite that, if you happen to call InsertPerson with NULL argument, your code would put new Person after the first one and cut the rest of the list off.
To put new Person to the end of the list when called with NULL you could use something like this in your InsertPerson function:
if(pFirst) {
Person *last = pFirst;
while(last->pNext != NULL) {
last = last->pNext;
}
last->pNext = pPersonNew;
pPersonNew->pPrev = last;
}
else
pFirst = pPersonNew;
Insertion according to position index might fail as well if you give a position index that is higher than there are nodes in the list. Some sort of safety check should be added as well.
pPersonCur = pFirst->pNext;
while (counter < position && pPersonCur->pNext != NULL) { // If last node reached, stop the loop
pPersonCur = pPersonCur->pNext;
counter++;
}
This implementation would add new Person to the end of the list if position index is too high.

Trouble with a sequential search algorithm

Also why does this give me an error because I used bool?
I need to use this sequential search algorithm, but I am not really sure how. I need to use it with an array. Can someone point me in the correct direction or something on how to use this.
bool seqSearch (int list[], int last, int target, int* locn){
int looker;
looker = 0;
while(looker < last && target != list[looker]){
looker++;
}
*locn = looker;
return(target == list[looker]);
}
Looks like you'd use it like this...
// I assume you've set an int list[], an int listlen and an int intToFind
int where;
bool found = seqSearch(list, listlen - 1, intToFind, &where);
if (found)
{
// list[where] is the entry that was found; do something with it
}
It's pretty clear
list[] is the list you are searching
last is the last index in the list
target is what you are searching in list
locn will contain the index at which target was found
the return value is a boolean indicating if the target was found
for your question how to pass locn, do something like
int locn; /* the locn where the index of target will be stored if found */
bool target_found = seqSearch(blah blah blah, &locn);
The problem with your code is if you search for an element not present in the array, looker will be equal to last and you try to access an array element at location last which is invalid.
Instead you can do:
bool seqSearch (int list[], int last, int target, int* locn) {
int looker;
for(looker=0;looker<last;looker++) {
// target found.
if(list[looker] == target) {
*locn = looker; // copy location.
return true; // return true.
}
}
// target not found.
*locn = -1; // copy an invalid location.
return false; // return false.
}
You call the function as follows:
int list[] = {5,4,3,2,1}; // the array to search in.
int size = sizeof(list)/sizeof(list[0]); // number of elements in the array.
int target = 3; // the key to search for.
int locn; // to hold the location of the key found..and -1 if not found.
if( seqSearch(list,size,target,&locn) ) {
// target found in list at location locn.
} else {
// target not found in list.
}
There are a few issues.
I would change the name of last to size.
If you don't find the value, you will dereference an invalid memory location.
EDIT: I guess last is the length - 1. That's an unusual signature. So the call is something like:
int list[CONSTANT];
...
int foundIndex;
bool found = seqSearch(list, sizeof(list)/sizeof(int), target, &foundIndex);
There are many ways to enable bool. One is to use stdbool.h with C99.

How to sort a stack using only Push, Pop, Top, IsEmpty, IsFull?

Given a stack S, need to sort the stack using only Push, Pop, Top, IsEmpty, IsFull.
Looking for most simple solution.
Edited: Removed in place condition. Can't use another stack or queue.
For this problem, can we consider using system stack? Make several recursive calls.
public static void sort(Stack<Integer> s) {
if (!s.isEmpty()) {
Integer t = s.pop();
sort(s);
insert(t, s);
}
}
private static void insert(Integer x, Stack<Integer> s) {
if (s.isEmpty()) {
s.push(x);
return;
}
if (x < s.peek()) {
Integer t = s.pop();
insert(x, s);
s.push(t);
} else {
s.push(x);
}
}
It can be done...
Ok: sorted, ahem, "in-place" with only the listed ops, didn't need Top() or IsFull() or another stack or data structure other than the call frames. (Presumably the whole point of the homework problem was to require a recursive solution.)
Ruby
#a = [3, 2, 1, 6, 5, 4]
class Array
def empty?
return size == 0
end
end
def sort e
if #a.empty?
#a.push e
return
end
t = #a.pop
if e > t
#a.push(t).push(e)
return
end
sort e
#a.push t
end
def resort
return if #a.empty?
t = #a.pop
resort
sort t
end
p ['first ', #a]
resort
p ['final ', #a]
techInterview Discussion - Sorting on Stack
More pseudo than anything, but there is code examples and possible solution.
Its not possible.
That happens because you cant iterate through the stack, because it has to be in place (you could if you would use extra memory). So if you cant iterate through the stack you cant even compare two elements of the stack. A sort without comparing would need extra memory, so that cant be used either.
Also im sure its not homework, because i dont think a teacher would give you a problem that cant be solved.
If you really have to do it only with stacks, just use 1-2 extra temporary stacks (i think 2 are needed, but not 100% sure) and do it.
You can't. You can't reorder the contents of a stack without removing elements, by definition. Also push and pop aren't in-place operations, so basically you're asking to sort a stack with Top, IsEmpty and IsFull. IsEmpty = !IsFull. So you're asking to sort a stack with Top and IsEmpty.
What temporary data structures can you use?
With push and pop, and no temporary storage for n elements, accessing data near the bottom of the stack would be impossible without storing the rest -somewhere-.
If top (equiv to {x=pop();push(x);return x}) was replaced with shift, it would be perfectly doable - the stack would change into fifo (shift+push; pop would fall into disuse) and it would allow for an easy bubblesort on currently available elements.
To bad you couldn't have two other stacks, then you could have played the Towers of Hanoi in O(n) space.
//A java version
public static void sort(Stack<Integer> s){
if(s.size() > 0){
int tmp = s.pop();
sort(s);
sortFromBottom(s, tmp);
}
}
private static void sortFromBottom(Stack<Integer> s, Integer value){
if(s.size() == 0){
s.add(value);
}else{
int tmpValue = s.peek();
if(tmpValue < value){
s.pop();
sortFromBottom(s, value);
s.push(tmpValue);
}else{
s.push(value);
}
}
}
Bubble Sort and Insert Sort in Java
https://github.com/BruceZu/sawdust/blob/82ef4729ee9d2de50fdceab2c8976d00f2fd3ba0/dataStructuresAndAlgorithms/src/main/java/stack/SortStack.java
/**
* Sort the stack using only Stack API, without using other data structure
* Ascending from bottom to top
*/
public class SortStack<T extends Comparable<T>> {
int sorted;
/**
* Just Bubble Sort.
*/
private void bubble(Stack<T> s, T max) {
if (s.empty() || s.size() == sorted) {
s.push(max);
sorted++;
return; // note return
}
T currentTop = s.pop();
if (max.compareTo(currentTop) < 0) {
T tmp = max;
max = currentTop;
currentTop = tmp;
}
bubble(s, max);
s.push(currentTop);
}
public Stack<T> sortAscending(Stack<T> s) {
sorted = 0;
if (s == null || s.size() <= 1) {
return s;
}
while (sorted != s.size()) {
bubble(s, s.pop());
}
return s;
}
/**
* Just Insert Sort.
*/
private void insertSort(Stack<T> s) {
if (s.empty()) {
return;
}
T currentTop = s.pop();
insertSort(s);
insert(s, currentTop);
}
private void insert(Stack<T> s, T insert) {
if (s.isEmpty() || insert.compareTo(s.peek()) <= 0) {
s.push(insert);
return;
}
T current = s.pop();
insert(s, insert);
s.push(current);
}
public Stack<T> sortAscendingByInsertSort(Stack<T> s) {
if (s == null || s.size() <= 1) {
return s;
}
insertSort(s);
return s;
}
}
Sorting a stack without extra space is quite not a possibility .
At least not coming to my sane mind .
We can surely use the recursion stack as extra space over here .
The below approach might be helful .
My approach is O(N**2) . Over here I am iterating over stack N times, every time fixing the ith element in the stack .
Firstly fixed the bottom element by popping out N elements and pushing min_element and in
Second try fixed the 2nd element from bottom by popping out N-1 elements and pushing min_element except the one pushed before this
And so on .
Refer to the code below for more details .
stack<int> stk;
int sort_util(stack<int> &stk,int n,int mn)
{
if(n==0)
{
stk.push(mn);
return mn;
}
int vl = stk.top();
stk.pop();
int fmin = sort_util(stk,n-1,min(mn,vl));
if(fmin==vl)
return INT_MAX;
else
stk.push(vl);
return fmin;
}
void sort_stack(stack<int> &stk)
{
for(int i=stk.size();i>1;i--)
sort_util(stk,i,stk.top());
}

Resources