I tried to get output after call insertNodeToEnd and displayNode. Bu I did not get any output. What is problem here?
#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
void displayNode(Node* head ){
while(head!=NULL){//starting pointimiz NULL olana kadar döndür
cout<<head->data<<endl; //NULL olana kadar her Node'un data'sını yazdı
head = head->next;//ilerle
}
}
void insertNodeToEnd(Node*curr , int data){
while(curr->next !=NULL){
curr = curr->next;
}
curr ->next ->data = data;
curr ->next->next = NULL;
}
Node* head; //başlangıc node'unun adresini tuttuk
int main(){
Node* Head = new Node; //bir node oluşturduk
Head -> next = NULL;
Head -> data = 500; //oluşan node'un datasını oluşturduk
Node *iter = Head; //linked list içerisinde dolşacak iterator
//bu iterator'u head olarak tuttuk(artık döngüde iter'i başlangıç olarak kullanacağız)
int i = 0;
for(i = 0 ; i<5 ; i++){
insertNodeToEnd(iter,i*10);
}
displayNode(Head);
}
I tried to get output after call insertNodeToEnd and displayNode. Bu I did not get any output. What is problem here?
The problem is your insertNodeToEnd() is implemented all wrong. It is not creating a new Node, it is accessing curr->next when it is not pointing at a valid node, and it is not taking into account the possibility of head being NULL when the list is empty.
Try something more like this instead:
#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
void displayNodes(Node* head){
while (head != NULL){
cout << head->data << endl;
head = head->next;
}
}
void insertNodeToEnd(Node* &head, int data){
Node *newNode = new Node;
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
Node *curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = newNode;
}
}
/* alternatively:
void insertNodeToEnd(Node* &head, int data) {
Node **curr = &head;
while (*curr != NULL) {
curr = &((*curr)->next);
}
*curr = new Node;
(*curr)->data = data;
(*curr)->next = NULL;
}
*/
void freeNodes(Node* head){
while (head != NULL){
Node *next = head->next;
delete head;
head = next;
}
}
int main(){
Node* head = NULL;
insertNodeToEnd(head, 500);
for(int i = 0; i < 5; ++i){
insertNodeToEnd(head, i*10);
}
displayNodes(head);
freeNodes(head);
}
Online Demo
That being said, consider using the standard std::list container instead, eg:
#include <iostream>
#include <list>
using namespace std;
void displayNodes(const list<int> &lst){
for (int elem : lst){
cout << elem << endl;
}
}
int main(){
list<int> lst;
lst.push_back(500);
for(int i = 0; i < 5; ++i){
lst.push_back(i*10);
}
displayNodes(lst);
}
Online Demo
Related
I wrote the following code to reverse a linked list recursively for my homework. However, It's not connecting the links properly. Can please someone tell me what's wrong in the following reverse function? I have tried GDB as well. But, could not figure out what's wrong?
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
explicit Node(int data)
{
this->data = data;
next = nullptr;
}
};
void pushBack(Node * &head, Node * &tail, int data)
{
if(head == nullptr)
{
head = new Node(data);
tail = head;
}
else
{
tail->next = new Node(data);
tail = tail->next;
}
}
void printList(Node *head)
{
if(head == nullptr)
return;
cout << head->data << " ";
printList(head->next);
}
void reverseListRecursive(Node * &head)
{
if(head->next == nullptr)
{
return;
}
reverseListRecursive(head->next);
head->next->next = head;
head->next = nullptr;
}
int main()
{
int cap;
cin >> cap;
Node *head = nullptr, *tail = nullptr;
for(int i = 0; i < cap; ++i)
{
int element;
cin >> element;
pushBack(head, tail, element);
}
reverseListRecursive(head);
printList(head);
return 0;
}
Head is being passed by reference and also the infinite recursion is also not there.
The problem is that the head pointer needs to point to the last node of the linked list. Following code fixes the problem.
void reverseListRecursive(Node * &head, Node *temp = nullptr)
{
if(temp == nullptr)
temp = head;
if(temp->next == nullptr)
{
head = temp;
return;
}
reverseListRecursive(head, temp->next);
temp->next->next = temp;
temp->next = nullptr;
}
I catched segfault when run this code and can`t understand why.
If firstly i use one time push(&head,3); then segfault is not catched, but it works bad for true
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
void push(Node **head,int data)
{
Node *tmp = new Node;
tmp->data = data;
tmp->next = (*head);
(*head) = tmp;
}
Node *getLast(Node *head)
{
if(head == nullptr)
{
return nullptr;
}
while(head->next)
{
head=head->next;
}
return head;
}
void show(const Node *head)
{
while(head!=nullptr)
{
cout << head->data << endl;
head = head->next;
}
}
void pushBack(Node *head,int data)
{
Node *last = getLast(head);
Node *tmp = new Node;
tmp->data = data;
tmp->next = nullptr;
last->next = tmp;
}
int main() {
Node *head=nullptr;
**//push(&head,2); /////if I use this then it works! but it not right.**
pushBack(head,10);
pushBack(head,2);
pushBack(head,3);
show(head);
return 0;
}
I tried to google it but it helpless.
How to solve this problem?
If the linked list is empty you have to modify head which requires to pass the reference of head. This should work:
void pushBack(Node **head,int data)
{
Node *last = getLast(*head);
Node *tmp = new Node;
tmp->data = data;
tmp->next = nullptr;
if(last == nullptr)
{
*head = tmp;
}
else
{
last->next = tmp;
}
}
int main() {
Node *head=nullptr;
pushBack(&head,10);
pushBack(&head,2);
pushBack(&head,3);
show(head);
return 0;
}
#include <iostream>
using namespace std;
class List {
public:
struct node {
int data;
node *next;
};
node* head = NULL;
node* tail = NULL;
node* temp = NULL;
node* prev = NULL;
public:
void addNum(int num) {
temp = new node;
temp->data = num;
temp->next = NULL;
if (head == NULL) {
head = temp;
tail = temp;
}
else {
tail->next = temp;
tail = temp;
}
}
void PrintList() {
temp = head;
while (temp != NULL) {
cout << temp->data << endl;
temp = temp->next;
}
}
void DelNum(int num) {
temp = head;
while (temp != NULL) {
if (temp->data == num) {
prev->next = temp->next;
free(temp);
}
temp = prev;
temp = temp->next;
}
}
};
int main() {
List list;
list.addNum(1);
list.addNum(2);
list.addNum(3);
list.addNum(4);
list.addNum(5);
list.addNum(6);
list.DelNum(3);
list.PrintList();
return 0;
}
What is wrong with my DelNum function? When I run the program nothing pops up. Doesn't matter what number I put in.
As mss pointed out the problem is in your DelNum() function where you assign temp = prev;. In your initialization you defined that node* prev = NULL; So, prev = NULL at the point when you assigned it to temp which caused segmentation fault when you try to use it like temp = temp->next;.
Two main problems are there in DelNum function:
first, when you are in while loop
, you should assign
prev = temp;
second, when you have found your target element, after deleting it you have to break out of the loop, which isn't done in your code
below is your corrected code( also correction of some other corner case in DelNum function ):
#include <iostream>
using namespace std;
class List {
public:
struct node {
int data;
node *next;
};
node* head = NULL;
node* tail = NULL;
node* temp = NULL;
node* prev = NULL;
public:
void addNum(int num) {
temp = new node;
temp->data = num;
temp->next = NULL;
if (head == NULL) {
head = temp;
tail = temp;
}
else {
tail->next = temp;
tail = temp;
}
cout<<num<<" is added \n";
}
void PrintList() {
temp = head;
while (temp != NULL) {
cout << temp->data << endl;
temp = temp->next;
}
}
void DelNum(int num) {
if(head==NULL)//empty
{
cout<<"empty linked list, can't be deleted\n";
return;
}
if(head->next==NULL)//means only one element is left
{
if(head->data==num)
{
node * fordelete=head;
head=NULL;
cout<<num<<"is deleted\n";
delete(fordelete);
}
else
{
cout<<"not found , can't be deleted\n";
}
return;
}
temp = head; // when more than one element are there
prev = temp;
while (temp != NULL) {
if (temp->data == num) {
prev->next = temp->next;
free(temp);
cout<<num<<" is deleted\n";
break;
}
prev= temp;
temp = temp->next;
}
if(temp==NULL)
{
cout<<"not found, can't be deleted\n";
}
}
};
int main() {
List list;
list.addNum(1);
list.addNum(2);
list.addNum(3);
list.addNum(4);
list.addNum(5);
list.addNum(6);
list.PrintList();
list.DelNum(3);
list.DelNum(7);
list.PrintList();
return 0;
}
I hope it will help you.
I don't know why PrintList() doesn't terminate. It is a LinkedList, so when I go to next, that should terminate.
When I do AddNode once and then print, that terminates, when I do addNode twice, print doesn't terminate.
The reason why in constructor I create 5 empty spots is because I'm required to create those 5 empty spots when program starts.
Moreover, if for example I add twice , how I can assign pointer to that second value?
#pragma once
class LinkedList
{
private:
typedef struct node {
int data;
node* next;
}* nodePtr;
nodePtr n;
nodePtr head;
nodePtr curr;
nodePtr temp;
public:
LinkedList();
void AddNode(int addData);
void PrintList();
~LinkedList();
};
#include "LinkedList.h"
#include<cstdlib>
#include<iostream>
using namespace std;
LinkedList::LinkedList()
{
head = NULL;
curr = NULL;
temp = NULL;
n = new node;
for (int x = 1; x <= 5; x++) {
//cout << n<<endl;
n->next = n;
}
}
void LinkedList::AddNode(int addData) {
//nodePtr n = new node;
n->next = NULL;
n->data = addData;
cout << n <<endl;
if (head != NULL) {
curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = n;
}
else {
head = n;
}
}
void LinkedList::PrintList() {
curr = head;
while (curr != NULL) {
cout << curr->data << endl;
curr = curr->next;
}
}
LinkedList::~LinkedList()
{
head = NULL;
curr = NULL;
temp = NULL;
delete n;
}
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include "LinkedList.h"
using namespace std;
int main() {
LinkedList *l = new LinkedList();
l->AddNode(5);
l->AddNode(8);
l->PrintList();
system("pause");
return 0;
}
The node n is always the same since you are not setting n to a different node
So when you do n->next and n->data , the same node is being modified each time
void LinkedList::AddNode(int addData) {
//nodePtr n = new node; // you need to uncomment this
n->next = NULL;
n->data = addData;
cout << n <<endl;
if (head != NULL) {
curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = n;
}
else {
head = n;
}
}
After your first addNode(5), lets examine the values.
head = n
head->data = 5
head->next = null
After your second addNode(8)
head = n
head->data = 8
head->next = n // set by "curr->next = n" .
So you have a problem here. When you try to loop through your linked list, it will become head->next->head->next->head->next->head->next ..... causing an infinite loop
I am trying to iterate over a vector and get the data into the linked list nodes... I know I can use the STL iterator for vector, but what can I use to loop over the linked list? I don't think I can use STL list iterator, right?
List.h
class List {
public:
List();
void addNode(int addData);
void deleteNode(int delData);
void printList();
private:
typedef struct Node {
int data;
Node* next;
}* nodePtr;
nodePtr head;
nodePtr curr;
nodePtr temp;
};
List.cpp
List::List() {
head = NULL;
curr = NULL;
temp = NULL;
}
void List::addNode(int addData){
nodePtr n = new Node;
n->next = NULL;
n->data = addData;
if(head != NULL) {
curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = n;
}
else {
head = n;
}
}
void List::deleteNode(int delData) {
nodePtr delPtr = NULL;
temp = head;
curr = head;
while(curr != NULL && curr->data != delData) {
temp = curr;
curr = curr->next;
}
if(curr == NULL) {
cout << delData << " was not in the list.\n";
delete delPtr;
}
else {
delPtr = curr;
curr = curr->next;
temp->next = curr;
if(delPtr == head) {
head = head->next;
temp = NULL;
}
delete delPtr;
}
}
void List::printList() {
curr = head;
while(curr !=NULL) {
cout << curr->data << endl;
curr= curr->next;
}
}
main.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
int main(int argc, char** argv) {
cout << "Enter some integers, space delimited:\n";
string someString;
getline(cin, someString);
istringstream stringStream( someString );
vector<int> integers;
int n;
while (stringStream >> n)
List listOfInts;
listOfInts.addNode(/* stuff in here*/)
integers.push_back(n);
return 0;
}
You don't need to iterate through the linked list. Use addNode to add items to the linked list.
vector<int> vec;
...
List list;
for (vector<int>::iterator i = vec.begin(); i != vec.end() ++i)
list.addNode(*i);
That's all there is to it.