226k views
2 votes
Can you fix my code. It keeps saying some errors.

Using uninitialized memory 'q'
SinglyLinkedList.h:
#pragma once
#include
#include
struct listNode {
int data;
struct listNode* next;
};
int singlyListLength(struct listNode* head) {
int count = 0;
struct listNode* current = head;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
void insertInSinglyLinkedList(struct listNode** head, int data, int pos) {
int k = 1;
struct listNode* q, * p;
struct listNode* newNode = (struct listNode*)malloc(sizeof(struct listNode));
if (newNode == NULL) {
printf("Memory Error\\");
return;
}
newNode->data = data;
p = *head;
if (pos == 1 || p == NULL) {
newNode->next = *head;
*head = newNode;
}
else {
while (p != NULL && (k < pos)) {
k++;
q = p;
p = p->next;
}
newNode->next = q->next;
q->next = newNode;
}
}
void deleteNodeFromLinkedList(struct listNode** head, int pos) {
int k = 1;
struct listNode* p, * q;
p = *head;
if (*head == NULL) {
printf("List Empty\\");
return;
}
else if (pos == 1) {
*head = (*head)->next;
free(p);
}
else {
while (p != NULL && k < pos) {
k++;
q = p;
p = p->next;
}
if (p == NULL) {
printf("Position does not exist\\");
}
else {
q->next = p->next;
free(p);
}
}
}
void printSLList(struct listNode* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\\");
}
Main.c
#include"SinglyLinkedList.h"
#include
#include
int SinglyLinkedList_test() {
struct listNode* head = NULL;
insertInSinglyLinkedList(&head, 5, 5);
insertInSinglyLinkedList(&head, 2, 5);
printf("Elements in List:%d\\", singlyListLength(head));
printSLList(head);
deleteNodeFromLinkedList(&head, 1);
printSLList(head);
return 0;
}

1 Answer

4 votes
Here’s the code in JavaScript:

// SinglyLinkedList.js
class ListNode {
constructor(data) {
this.data = data;
this.next = null;
}
}

class SinglyLinkedList {
constructor() {
this.head = null;
}

listLength() {
let count = 0;
let current = this.head;

while (current !== null) {
count++;
current = current.next;
}

return count;
}

insertNode(data, pos) {
let k = 1;
let q, p;
let newNode = new ListNode(data);

if (newNode === null) {
console.log("Memory Error");
return;
}

p = this.head;

if (pos === 1 || p === null) {
newNode.next = this.head;
this.head = newNode;
} else {
while (p !== null && k < pos) {
k++;
q = p;
p = p.next;
}

newNode.next = q.next;
q.next = newNode;
}
}

deleteNode(pos) {
let k = 1;
let p, q;
p = this.head;

if (this.head === null) {
console.log("List Empty");
return;
} else if (pos === 1) {
this.head = this.head.next;
p = null;
return;
} else {
while (p !== null && k < pos) {
k++;
q = p;
p = p.next;
}

if (p === null) {
console.log("Position does not exist");
} else {
q.next = p.next;
User Buddy Bob
by
8.3k points