Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
The code hangs while executing. Please help me to understand what is the problem here
It stcks after the first travers and does not even enters the reverse function. Could not understand the issue:
Help me on it.
# include<iostream>
# include<stdlib.h>
using namespace std;
struct sLL
{
int data;
sLL * next;
};
void createList(sLL ** head, int n)
{
if(n == 0)
{
return;
}
sLL * temp = (sLL *) malloc(sizeof(sLL));
if(temp != NULL)
{
temp->data = rand() % 100;
temp->next = NULL;
*head = temp;
//head = &(temp->next);
createList(&(temp->next), n - 1);
}
}
void traverse(sLL * head)
{
cout<<"In traverse"<<endl;
while(head) {
cout<<head->data<<"->";
head=head->next;
}
cout<<"NULL"<<endl;
cout.flush();
return;
}
sLL* reverse(sLL * head)
{
sLL * temp = NULL, * newNode = NULL;
while(head) {
newNode = head->next; // to traverse forword
head->next = temp;
temp = head; // Current node value which we use in next itr as a previous node value.
newNode = head; // assigning newNode vlaue back to head so that we can traverse forward.
}
return temp; // final node value will be in temp i.e the current node value.
}
int main()
{
int n;
sLL * head = NULL, *temp = NULL;
cout<<"Enter the number of nodes :";
cin>>n;
createList(&head, n);
cout<<"\nCreate Done"<<endl;
traverse(head);
cout.flush();
cout<<"Reverse Start";
temp = reverse(head);
cout<<"reverse done";
traverse(temp);
}
You don't reassign the head value at all
while(head)
//loop
Here, the head pointer is never altered. So the loop is an infinite one.
Your comment contradicts the code here:
newNode = head; // assigning newNode vlaue back to head so that we can traverse forward.
If you do what the comment says it should work better:
head = newNode; // assigning newNode value back to head so that we can traverse forward.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
Im trying to create function to delete from single-linked list all elements with value smaller as next (following) element value. For some reason programm throws "free():double free detected in tcache 2". What is wrong with my function ?
list is not empty.
#include <iostream>
using namespace std;
struct Elem
{
int num;
Elem* next;
};
void deleteFromLinkedList(Elem* list) {
Elem* curr, * next, *prev;
curr = list;
next = list->next;
while (next != NULL)
{
if (curr->num < next->num) {
prev->next=next;
delete curr;
curr = prev;
continue;
}
prev = curr;
curr = next;
next = curr->next;
};
}
int main()
{
Elem* first = NULL, * last = NULL, * p;
int i;
cout << "Enter any number or 0 to finish: ";
cin >> i;
while (i != 0)
{
p = new Elem;
p->num = i;
p->next = NULL;
if (first == NULL)
{
first = last = p;
}
else
{
last->next = p;
last = last->next;
};
cout << "Enter any number or 0 to finish: ";
cin >> i;
};
deleteFromLinkedList(first);
There are a number of problems with your code.
next = list->next; is undefined behavior if the list is empty (ie list is null).
prev->next=next; is undefined behavior for the 1st node in the list, as prev is unassigned.
You are not updating curr after delete'ing the node it points at, which is also undefined behavior.
The list pointer is being passed in by value, so the caller's pointer can't be updated if the 1st node in the list is freed, thue the caller will be left with a dangling pointer to invalid memory.
Try this instead:
void deleteFromLinkedList(Elem* &list) {
if (!list)
return;
Elem *curr = list, *next = list->next, *prev = NULL;
while (next)
{
if (curr->num < next->num) {
if (prev)
prev->next = next;
else
list = next;
delete curr;
}
else {
prev = curr;
}
curr = next;
next = curr->next;
}
}
Online Demo
UPDATE: In comments, you changed your requirements to need the list scanned in multiple iterations. The code above works fine for 1 iteration, so you could simply call it multiple times in a loop until there are no more removals performed, eg:
bool deleteFromLinkedList(Elem* &list) {
if (!list)
return false;
Elem *curr = list, *next = list->next, *prev = NULL;
bool anyRemoved = false;
while (next)
{
if (curr->num < next->num) {
if (prev)
prev->next = next;
else
list = next;
delete curr;
anyRemoved = true;
}
else {
prev = curr;
}
curr = next;
next = curr->next;
}
return anyRemoved;
}
...
while (deleteFromLinkedList(first));
...
Online Demo
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 months ago.
Improve this question
Please help me find the error in the given code, After returning the new head and using the printing function, no output gets displayed
Node *interChange(Node *head, int n){
Node *tempoo = head;
Node *temp = head;
int tot =0;
while(tempoo != NULL){
tempoo = tempoo->next;
tot++;
}
int count =0;
while(count < tot-n){
temp=temp->next;
count++;
}
Node *newHead = temp->next;
temp->next=NULL;
Node *newTemp = newHead;
while(newTemp != NULL){
newTemp = newTemp->next;
}
newTemp->next = head;
return newHead;
}
The last statement before the return performs an invalid dereferencing: newTemp->next = head; when at that point it is guaranteed that newTemp is NULL. This leads to undefined behaviour.
Your function returns the new head, so make sure the caller (which you didn't include) will use that new head pointer when printing the list.
Some other remarks:
The code does not deal well when the list is empty
The code does not deal well when n is greater than the number of nodes in the list, or is negative. It would maybe be a good idea to use modulo arithmetic to bring that value in range.
The cutoff point is wrongly calculated. For n is 0, the original head node will still become the new tail (if all the rest is corrected).
In C++ you should be using nullptr instead of NULL
Calling all your variables something like temp is not helpful. You can do with fewer variables, and use more telling names.
Here is a correction to your function:
Node *interChange(Node *head, int n) {
if (head == nullptr) return nullptr; // Boundary case
Node *tail = head;
int tot = 1; // We already have the head
// Check whether there is a next node, so we end up with the tail
while (tail->next != nullptr) {
tail = tail->next;
tot++;
}
// Make list circular
tail->next = head;
// Bring the n argument within a valid range
n %= tot;
// Find new tail
for (int count = tot - n; count; count--) {
tail = tail->next; // Reuse tail variable to identify new tail
}
// Reuse variable to identify new head
head = tail->next;
// Make list non-circular again
tail->next = nullptr;
return head;
}
The caller should capture the returned pointer. For instance:
Node *head;
// Initialise head with a list ...
// (your code here)
// And then:
head = interChange(head, 3);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to make a function that adds at the end of a linked list but I get a segmentation fault.
I don't really know what's wrong with my code. I first check if the list is empty. If it is not empty then I first find the end of the list using n I use a while loop to do this, then once that loop is done I then set n->next = tmp;
struct Node {
int data;
struct Node *next;
};
typedef Node Node;
void add(Node* &head, int data) {
Node *tmp = new Node;
tmp->data = data;
tmp->next = NULL;
if (!head) {
head->next = tmp;
} else {
Node *n = head;
while (n->next) {
n= n->next;
}
n->next = tmp;
}
}
int main() {
Node *head = NULL;
add(head,1);
add(head,2);
Node *tmp = head;
while (tmp != NULL) {
cout << tmp->data;
tmp = tmp->next;
}
}
When head is NULL, you are doing:
if (!head) {
head->next = tmp;
}
but there is no next for a NULL pointer, so this invokes undefined behavior.
You should instead do:
if (!head) {
head = tmp;
}
Here's a demo.
Also, avoid the NULL macro, and use nullptr instead.
head->next = tmp;
does not work since head is a nullptr when you enter that branch of code. It needs to be
head = tmp;
As a coding guideline,
You don't need struct Node* next. It can be just Node* next.
You don't need typedef Node Node.
struct Node {
int data;
Node *next;
};
// No need of this
// typedef Node Node;
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I want an explanation for how I can get to the Nth node in the linked list as to insert a node after that Nth node I have this piece of code and the function for inserting a node after the nth node is given as
InsertAfter
I have problem as how to call the function InsertAfter in the driver main function i.e. if i have to go to the node next to the head I may write as head -> next but, is this necessary to write next -> next for the elements to go beyond the second node . Is there any simple way which help me not to write next for every node to jump to the next node.
For examples --> If I have to insert node after 7, I have to write head-> next-> next but is there any easy way in which there is no need to next again and again.
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node* next;
};
Node* head = NULL;
void insert(int x)
{
Node* temp = new Node();
temp -> data = x;
temp -> next = head;
head = temp;
}
void display(){
Node* temp;
temp = head;
while(temp != NULL)
{
cout<< temp -> data<< " ";
temp = temp-> next;
}
}
void insertAtLast(int x)
{
Node* temp = new Node();
Node* last = head;
temp -> data = x;
temp -> next = NULL;
if(head == NULL)
{
head = temp;
return;
}
while (last -> next != NULL)
{
last = last-> next;
}
last -> next = temp;
return;
}
void InsertAfter(Node* prev, int data)
{
if(prev == NULL)
{
cout<< "The previous node cannot be NULL" << endl;
return;
}
Node* temp = new Node();
temp -> data = data;
temp -> next = prev -> next;
prev->next = temp;
}
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The linked list is: \n";
display();
cout<< endl;
insertAtLast(6);
display();
std::cout << '\n';
InsertAfter(head->,3);
display();
return 0;
}
To get to the Nth node, you follow the links, decrementing the counter, until the counter is zero or the end of the list is reached:
Node * at(unsigned int index)
{
Node * p = head;
while (p && (index != 0))
{
p = p->next;
--index;
}
return p;
}
"how I can get to the Nth node in the linked list as to insert a node after that Nth node" - Traverse the list until you get to the Nth node. Then insert.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Please help me with my code. I am trying to insert in a singly linked list.My code is compiling but it is giving a run time error.I am not able to understand where i have gone wrong.Here goes my code :-
#include <iostream.h>
#include <stdio.h>
using namespace std;
struct node
{
int info;
struct node* next;
};
typedef struct node* nodeptr;
void insert(nodeptr p,int x);
void print(nodeptr p);
int main()
{
nodeptr head;
head = NULL;
int num;
do
{
cout<<"ENTER A NUMBER(0 to terminate) :-\n";
cin >>num;
insert(head,num);
}
while (num != 0);
print(head);
}
void insert(nodeptr p,int x)
{
nodeptr tmp = new node;
tmp -> info = x;
tmp -> next = NULL;
nodeptr current;
current = p;
if (p == NULL)
{
p = tmp;
}
if (x < p -> info)
{
tmp->next = p;
p = tmp;
}
while((current->next != NULL) && (x >= (current->next)->info))
{
current = current -> next;
}
tmp->next = current->next;
current->next = tmp;
}
void print(nodeptr p)
{
nodeptr current;
current = p;
while(current != NULL)
{
int tmp = current->info;
cout << tmp;
current = current->next;
}
}
First of all, you never assign anything to head, so print(head) will not print anything.
Second, that last while in the main is useless.
Third:
nodeptr insert(nodeptr head, int x)
{
nodeptr tmp = new node;
tmp -> info = x;
tmp -> next = NULL;
nodeptr prec = null;
nodeptr current = head;
while(current != null && x < current->info)
{
prec = current;
current = current -> next;
}
tmp->next = current;
if(prec != null)
prec->next = tmp;
else
return tmp;
return head;
}
and in the main
head = insert(head, num);
When dealing with pointers, always try to keep things separated: first seek, then modify.