Keep getting seg fault with linked list - linked-list

I am new here and I am having problems making a linked list. I keep getting a segmentation fault and am not sure where the problem is. It keeps happening when I try to enter the function scanzip. I only included up to the code that stopped working. When running in visual studio, it gives an access violation on the line in scapzip with the while loop.
thanks
thanks
typedef struct houseType house;
struct houseType {
unsigned long int id;
int value;
int bedrooms;
float bathrooms;
int sqft;
int yr_built;
int zipcode;
house * nextzip; // One pointer for list of ordered zipcodes and one for ordered years
house * nextyr;
};
house * scanzip(house * head, int zip) { //Finds out where to put node based on zipcode
house * prev = NULL, * cur = NULL;
prev = head;
cur = head - > nextzip;
while ((cur != NULL) && (cur - > zipcode < zip)) {
prev = cur;
cur = cur - > nextzip;
}
return prev;
}
house * scanyr(house * head, int yr) { // Finds out where to put node based on yr_built
house * previous = NULL, * current = NULL;
previous = head;
current = head - > nextyr;
while ((current != NULL) && (current - > yr_built < yr)) {
previous = current;
current = current - > nextyr;
}
return previous;
}
int main() {
house * previous = NULL, * current = NULL, * head = NULL, * newnode = NULL, * zip = NULL, * prezip = NULL, * yr = NULL, * preyr = NULL;
head = (house * ) malloc(sizeof(house));
previous = head;
current = head - > nextzip;
float aveValue = 0;
float aveBed = 0;
float aveSize = 0;
int max = previous - > value;
int min = previous - > value;
int yrMax, yrMin;
int counter = 1;
int maxZip = previous - > zipcode, minZip = previous - > zipcode;
int tempbed, tempyr, tempzip, tempvalue, tempsqft;
unsigned long int tempid;
float tempbath;
char a[1000];
FILE * data = NULL;
fopen_s( & data, "c:/Users/joel/Downloads/house-info-v4.txt", "r");
if (fgets(a, 100, data) != "\n") // Gets rid of first line of file
puts(a);
fscanf_s(data, "%lu,%d,%d,%f,%d,%d,%d", & tempid, & tempvalue, & tempbed, & tempbath, & tempsqft, & tempyr, & tempzip);
head - > id = tempid;
head - > value = tempvalue;
head - > bedrooms = tempbed;
head - > bathrooms = tempbath;
head - > sqft = tempsqft;
head - > yr_built = tempyr;
head - > zipcode = tempzip;
printf("%lu,%d,%d,%f,%d,%d,%d\n", head - > id, head - > value, head - > bedrooms, head - > bathrooms, head - > sqft, head - > yr_built, head - > zipcode);
while (fscanf_s(data, "%lu,%d,%d,%f,%d,%d,%d", & tempid, & tempvalue, & tempbed, & tempbath, & tempsqft, & tempyr, & tempzip)) {
printf("%lu,%d,%d,%f,%d,%d,%d", tempid, tempvalue, tempbed, tempbath, tempsqft, tempyr, tempzip);
newnode = (house * ) malloc(sizeof(house)); //Allocates memory to a new node
newnode - > id = tempid;
newnode - > value = tempvalue;
newnode - > bedrooms = tempbed;
newnode - > bathrooms = tempbath;
newnode - > sqft = tempsqft;
newnode - > yr_built = tempyr;
newnode - > zipcode = tempzip;
newnode - > nextzip = NULL;
newnode - > nextyr = NULL;
printf("yes");
zip = scanzip(head, newnode - > zipcode);

Related

How to fix Close[1] & Close[2]

I have a problem with my EA trades, now I will show you the code with a screenshot of a trade (it happens often)
I see that I was definitely wrong for how the entry below must read I put an image where it explains what I have in mind
void OnTimer()
{
//---
if (currBars != Bars){
calculate_price_levels();
//debug_levels();
check_nearest_levels();
if (is_session()){
if (Close[2] < Nearest_Up_Level && Close[1] >= Nearest_Up_Level && isAvailableOrder()){
//Print("BUY entry, Nearest_Up_Level:",Nearest_Up_Level, ",Close[2]:",Close[2], ",Close[1]:",Close[1]);
double lot = _get_lot_size (Stop_Loss);
OpenTrade(Symbol(), OP_BUY, lot);
}
if (Close[2] > Nearest_Down_Level && Close[1] <= Nearest_Down_Level && isAvailableOrder()){
//Print("SELL entry, Nearest_Down_Level:",Nearest_Down_Level, ",Close[2]:",Close[2], ",Close[1]:",Close[1]);
double lot = _get_lot_size (Stop_Loss);
OpenTrade(Symbol(), OP_SELL, lot);
}
}
currBars = Bars;
}
if (Trailing_Stop > 0) trail_sl();
// if (BE > 0) check_be();
int trades_number = _get_number_of_trades();
if (trades_number < Trades_Number_0) check_last_trade_result();
Trades_Number_0 = trades_number;
}
void check_nearest_levels(){
int size = ArraySize(Price_Levels);
for (int i = 0; i < size; i++){
if (Close[2] > Price_Levels[i] && Close[2] < Price_Levels[i + 1]){
Nearest_Down_Level = Price_Levels[i];
Nearest_Up_Level = Price_Levels[i + 1];
BUY_TP_Price = 0;
if (size > i + 2) BUY_TP_Price = Price_Levels[i + 2];
else BUY_TP_Price = Nearest_Up_Level + StepPips * Point * mp;
Next_BUY_TP_Price = 0;
if (size > i + 3) Next_BUY_TP_Price = Price_Levels[i + 3];
else Next_BUY_TP_Price = BUY_TP_Price + StepPips * Point * mp;
SELL_TP_Price = 0;
if (i >= 1) SELL_TP_Price = Price_Levels[i - 1];
else SELL_TP_Price = Nearest_Down_Level - StepPips * Point * mp;
Next_SELL_TP_Price = 0;
if (i >= 2) Next_SELL_TP_Price = Price_Levels[i - 2];
else Next_SELL_TP_Price = SELL_TP_Price - StepPips * Point * mp;
break;
}
}
}
Example of what I want to do

Network Delay Problem - Complexity Analysis

Below is a solution Network delay problem of leetcode. I have written a all test case success solution. But not able to analyse the time complexity. I believe its O(V^2 + E) where V is the number of nodes and E edges.
In this solution though I am adding all adjacents of each node every time, but not processing them further if there exists a min distance for that node already.
Leetcode question link https://leetcode.com/problems/network-delay-time
public int networkDelayTime(int[][] times, int n, int k) {
int[] distances = new int[n+1];
Arrays.fill(distances , -1);
if(n > 0){
List<List<int[]>> edges = new ArrayList<List<int[]>>();
for(int i = 0 ; i <= n ; i++){
edges.add(new ArrayList<int[]>());
}
for(int[] time : times){
edges.get(time[0]).add(new int[]{time[1] , time[2]});
}
Queue<Vertex> queue = new LinkedList<>();
queue.add(new Vertex(k , 0));
while(!queue.isEmpty()){
Vertex cx = queue.poll();
int index = cx.index;
int distance = cx.distance;
//process adjacents only if distance is updated
if(distances[index] == -1 || distances[index] > distance){
distances[index] = distance;
List<int[]> adjacents = edges.get(index);
for(int[] adjacent : adjacents){
queue.add(new Vertex(adjacent[0] , adjacent[1]+distance));
}
}
}
}
int sum = 0;
for(int i = 1 ; i <= n; i++){
int distance = distances[i];
if(distance == -1){
return -1;
}
sum = Math.max(sum , distance);
}
return sum;
}
public static class Vertex{
int index;
int distance;
public Vertex(int i , int d){
index = i;
distance = d;
}
}
You should use PriorityQueue instead of LinkedList

Round Robin Algorithm Using Circular Linked List

Use a circular singly linked list to implement Round Robin process scheduling algorithm in which
each process is provided a fixed time (quantum) to execute and is pre-empted after that time period
to allow the other process to execute. Assume a set of ‘n’ processes are ready for execution.
Read the time quantum and for each of the processes, read the total execution time.
Name the processes as ‘A’, ‘B’ and so on in sequence. Each node should contain the name
of the process, its total execution time and the remaining execution time. If a process
completes its execution, remove it from the list after displaying its name and the
completion time.
Input format:
First line contains the value of ‘n’, the number of processes
Second line contains the time quantum
The remaining lines contain the total execution time of the processes in order.
5
2
6
3
7
5
1
Output:
E 9
B 12
A 18
D 21
C 22
#include <iostream>
using namespace std;
class node
{
public:
char name;
int tm;
int rt;
node *next;
};
class rr
{
public:
node * Head = NULL;
int j = 65;
void insert (int n)
{
node *nn = new node;
nn->name = j++;
nn->tm = n;
nn->rt = nn->tm;
if (Head == NULL)
{
Head = nn;
Head->next = Head;
}
else
{
node *temp = Head;
while (temp->next != Head)
temp = temp->next;
nn->next = temp->next;
temp->next = nn;
}
}
void quantum (int t)
{
node *temp = Head;
int c = 0, i = 0;
while (Head != NULL)
{
{
temp->rt = temp->rt - t;
c = c + t;
if (temp->rt <= 0)
{
c = c + temp->rt;
cout << temp->name;
cout << c << endl;
del (temp->name);
if (temp->next == temp)
{
break;
}
}
temp = temp->next;
}
}
}
void del (char x)
{
node *p = NULL;
node *temp = Head;
if (Head->name == x)
{
while (temp->next != Head)
temp = temp->next;
p = Head;
temp->next = Head->next;
Head = Head->next;
delete p;
}
else
{
while (temp->name != x)
{
p = temp;
temp = temp->next;
}
p->next = temp->next;
delete temp;
}
}
};
int
main ()
{
rr robin;
int i, n, x, y, t;
cin >> y;
cin >> t;
for (i = 0; i < y; i++)
{
cin >> n;
robin.insert (n);
}
robin.quantum (t);
return 0;
}

Vehicle Speed Estimation via Blob Opencv C++

bool checkIfBlobsCrossedTheLine2(std::vector<Blob> &blobs, int &intHorizontalLinePosition,int &intHorizontalLinePosition2, cv::Mat &imgFrame2Copy) {
bool blnAtLeastOneBlobCrossedTheLine = false;
for (auto blob : blobs) {
if (blob.blnStillBeingTracked == true && blob.centerPositions.size() >= 2) {
int prevFrameIndex = (int)blob.centerPositions.size() - 2;
int currFrameIndex = (int)blob.centerPositions.size() - 1;
if ((blob.centerPositions[prevFrameIndex].y > intHorizontalLinePosition && blob.centerPositions[currFrameIndex].y <= intHorizontalLinePosition)&&(blob.centerPositions[prevFrameIndex].y > intHorizontalLinePosition2 && blob.centerPositions[currFrameIndex].y <= intHorizontalLinePosition2)) {
int time = 30;
int distance = 200;
int speed = distance/time;
double dblFontScale = blobs[currFrameIndex].dblCurrentDiagonalSize / 10.0;
int intFontThickness = (int)std::round(dblFontScale * 1.0);
std::cout<<"Speed: "<<speed<<std::endl;
cv::putText(imgFrame2Copy, std::to_string(speed), blobs[currFrameIndex].centerPositions.back(), CV_FONT_HERSHEY_SIMPLEX, dblFontScale, SCALAR_RED, intFontThickness);
blnAtLeastOneBlobCrossedTheLine = true;
}
}
}
return blnAtLeastOneBlobCrossedTheLine;
}
Please I didn't understand why I can't display the speed of each vehicle,
so help please

wrong perspective image after taking picture on accelerometer supported blackberry device

There is a perspective image issue when I read a picture that is taken from the camera. When the direction is north, the picture looks like needed to be rotated 270 degrees. When the direction is east, picture should be rotated 180 degrees. But it's good when the direction is west. I tried getMetaData().getKeyValue("orientation") in EncodedImage for producing a good rotating formula, but it returned empty string. Please help me how to solve this problem.
Found solution here:
https://gist.github.com/3788313
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
public class ExifRotate {
/**
* Flip the image horizontally.
*/
public static final int FLIP_H = 1;
/**
* Flip the image vertically.
*/
public static final int FLIP_V = 2;
/**
* Flip the image horizontally and vertically.
*/
public static final int FLIP_HV = 3;
/**
* Rotate the image 90 degrees clockwise.
*/
public static final int FLIP_90CW = 4;
/**
* Rotate the image 90 degrees counter-clockwise.
*/
public static final int FLIP_90CCW = 5;
/**
* Rotate the image 180 degrees.
*/
public static final int FLIP_180 = 6;
private final static int read2bytes(InputStream in) throws IOException {
return in.read() << 8 | in.read();
}
private final static int readByte(InputStream in) throws IOException {
return in.read();
}
public static Bitmap readImageFromFile(String filename, int width, int height) throws IOException {
EncodedImage img = null;
byte[] data = null;
FileConnection file = null;
try {
file = (FileConnection) Connector.open(filename, Connector.READ);
int fileSize = (int) file.fileSize();
if (fileSize == 0) {
throw new IOException("File is empty");
}
data = new byte[fileSize];
InputStream input = file.openInputStream();
input.read(data);
input.close();
img = EncodedImage.createEncodedImage(data, 0, data.length);
int orientation = -1;
if ( filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg")) {
ByteArrayInputStream is = new ByteArrayInputStream( data );
orientation = getRotation(is);
}
if ( orientation == 2 ) {
return rotateBitmap(img.getBitmap(), ImageUtil.FLIP_H);
} else if ( orientation == 3 ) {
return rotateBitmap(img.getBitmap(), ImageUtil.FLIP_180);
} else if ( orientation == 4 ) {
return rotateBitmap(img.getBitmap(), ImageUtil.FLIP_V);
} else if ( orientation == 5 ) {
Bitmap tmp = rotateBitmap(img.getBitmap(), ImageUtil.FLIP_H);
tmp = rotateBitmap(tmp, ImageUtil.FLIP_90CCW);
return tmp;
} else if ( orientation == 6 ) {
return rotateBitmap(img.getBitmap(), ImageUtil.FLIP_90CW);
} else if ( orientation == 7 ) {
Bitmap tmp = rotateBitmap(img.getBitmap(), ImageUtil.FLIP_H);
tmp = rotateBitmap(tmp, ImageUtil.FLIP_90CW);
return tmp;
} else if ( orientation == 8 ) {
return rotateBitmap(img.getBitmap(), ImageUtil.FLIP_90CCW);
} else {
return img.getBitmap();
}
} finally {
if (file != null) {
try { file.close(); }
catch(Exception ex){}
}
}
}
public static int getRotation(InputStream in) throws IOException {
int [] exif_data = new int[100];
int n_flag = 0, set_flag = 0;
int is_motorola = 0;
/* Read File head, check for JPEG SOI + Exif APP1 */
for (int i = 0; i < 4; i++)
exif_data[i] = readByte(in);
if (exif_data[0] != 0xFF || exif_data[1] != 0xD8 || exif_data[2] != 0xFF || exif_data[3] != 0xE1)
return -2;
/* Get the marker parameter length count */
int length = read2bytes(in);
// exif_data = new int[length];
/* Length includes itself, so must be at least 2 */
/* Following Exif data length must be at least 6 */
if (length < 8)
return -1;
length -= 8;
/* Read Exif head, check for "Exif" */
for (int i = 0; i < 6; i++)
exif_data[i] = in.read();
if (exif_data[0] != 0x45 || exif_data[1] != 0x78 || exif_data[2] != 0x69 || exif_data[3] != 0x66 || exif_data[4] != 0 || exif_data[5] != 0)
return -1;
/* Read Exif body */
length = length > exif_data.length ? exif_data.length : length;
for (int i = 0; i < length; i++)
exif_data[i] = in.read();
if (length < 12)
return -1; /* Length of an IFD entry */
/* Discover byte order */
if (exif_data[0] == 0x49 && exif_data[1] == 0x49)
is_motorola = 0;
else if (exif_data[0] == 0x4D && exif_data[1] == 0x4D)
is_motorola = 1;
else
return -1;
/* Check Tag Mark */
if (is_motorola == 1) {
if (exif_data[2] != 0)
return -1;
if (exif_data[3] != 0x2A)
return -1;
} else {
if (exif_data[3] != 0)
return -1;
if (exif_data[2] != 0x2A)
return -1;
}
/* Get first IFD offset (offset to IFD0) */
int offset;
if (is_motorola == 1) {
if (exif_data[4] != 0)
return -1;
if (exif_data[5] != 0)
return -1;
offset = exif_data[6];
offset <<= 8;
offset += exif_data[7];
} else {
if (exif_data[7] != 0)
return -1;
if (exif_data[6] != 0)
return -1;
offset = exif_data[5];
offset <<= 8;
offset += exif_data[4];
}
if (offset > length - 2)
return -1; /* check end of data segment */
/* Get the number of directory entries contained in this IFD */
int number_of_tags;
if (is_motorola == 1) {
number_of_tags = exif_data[offset];
number_of_tags <<= 8;
number_of_tags += exif_data[offset + 1];
} else {
number_of_tags = exif_data[offset + 1];
number_of_tags <<= 8;
number_of_tags += exif_data[offset];
}
if (number_of_tags == 0)
return -1;
offset += 2;
/* Search for Orientation Tag in IFD0 */
for (;;) {
if (offset > length - 12)
return -1; /* check end of data segment */
/* Get Tag number */
int tagnum;
if (is_motorola == 1) {
tagnum = exif_data[offset];
tagnum <<= 8;
tagnum += exif_data[offset + 1];
} else {
tagnum = exif_data[offset + 1];
tagnum <<= 8;
tagnum += exif_data[offset];
}
if (tagnum == 0x0112)
break; /* found Orientation Tag */
if (--number_of_tags == 0)
return -1;
offset += 12;
}
/*
* if (set_flag==1) { Set the Orientation value if (is_motorola==1) {
* exif_data[offset+2] = 0; Format = unsigned short (2 octets)
* exif_data[offset+3] = 3; exif_data[offset+4] = 0; Number Of
* Components = 1 exif_data[offset+5] = 0; exif_data[offset+6] = 0;
* exif_data[offset+7] = 1; exif_data[offset+8] = 0; exif_data[offset+9]
* = set_flag; exif_data[offset+10] = 0; exif_data[offset+11] = 0; }
* else { exif_data[offset+2] = 3; Format = unsigned short (2 octets)
* exif_data[offset+3] = 0; exif_data[offset+4] = 1; Number Of
* Components = 1 exif_data[offset+5] = 0; exif_data[offset+6] = 0;
* exif_data[offset+7] = 0; exif_data[offset+8] = set_flag;
* exif_data[offset+9] = 0; exif_data[offset+10] = 0;
* exif_data[offset+11] = 0; } }
*/
// else {
/* Get the Orientation value */
if (is_motorola == 1) {
if (exif_data[offset + 8] != 0)
return -1;
set_flag = exif_data[offset + 9];
} else {
if (exif_data[offset + 9] != 0)
return -1;
set_flag = exif_data[offset + 8];
}
if (set_flag > 8)
return -1;
// }
/* Write out Orientation value */
if (n_flag == 1)
System.out.println("set_flag " + set_flag);
else
System.out.println("set_flag " + set_flag);
return set_flag;
}
public static Bitmap rotateBitmap(Bitmap src, int operation) {
int width = src.getWidth();
int height = src.getHeight();
int[] inPixels = new int[width*height];
src.getARGB(inPixels, 0, width, 0, 0, width, height);
int x = 0, y = 0;
int w = width;
int h = height;
int newX = 0;
int newY = 0;
int newW = w;
int newH = h;
switch (operation) {
case FLIP_H:
newX = width - (x + w);
break;
case FLIP_V:
newY = height - (y + h);
break;
case FLIP_HV:
newW = h;
newH = w;
newX = y;
newY = x;
break;
case FLIP_90CW:
newW = h;
newH = w;
newX = height - (y + h);
newY = x;
break;
case FLIP_90CCW:
newW = h;
newH = w;
newX = y;
newY = width - (x + w);
break;
case FLIP_180:
newX = width - (x + w);
newY = height - (y + h);
break;
}
int[] newPixels = new int[newW * newH];
int index, newRow, newCol, newIndex;
if ( operation == FLIP_H ) {
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
index = row * width + col;
newRow = row;
newCol = w - col - 1;
newIndex = newRow * newW + newCol;
newPixels[newIndex] = inPixels[index];
}
}
} else if ( operation == FLIP_V ) {
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
index = row * width + col;
newRow = h - row - 1;
newCol = col;
newIndex = newRow * newW + newCol;
newPixels[newIndex] = inPixels[index];
}
}
} else if ( operation == FLIP_HV ) {
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
index = row * width + col;
newRow = col;
newCol = row;
newIndex = newRow * newW + newCol;
newPixels[newIndex] = inPixels[index];
}
}
} else if ( operation == FLIP_90CW ) {
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
index = row * width + col;
newRow = col;
newCol = h - row - 1;
newIndex = newRow * newW + newCol;
newPixels[newIndex] = inPixels[index];
}
}
} else if ( operation == FLIP_90CCW ) {
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
index = row * width + col;
newRow = w - col - 1;
newCol = row;
newIndex = newRow * newW + newCol;
newPixels[newIndex] = inPixels[index];
}
}
} else if ( operation == FLIP_180 ) {
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
index = row * width + col;
newRow = h - row - 1;
newCol = w - col - 1;
newIndex = newRow * newW + newCol;
newPixels[newIndex] = inPixels[index];
}
}
}
Bitmap dst = new Bitmap( newW, newH );
dst.setARGB(newPixels, 0, newW, 0, 0, newW, newH);
return dst;
}
}

Resources