iterating through a linked list inserting STL vector values - c++

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.

Related

why am i not getting output - Data Structure , Linked List

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

deleting a linked list node, C++ function not working

#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.

Print function doesn't terminate

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

C++ Linked List deleting the wrong item [closed]

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 years ago.
Improve this question
I'm trying to review data structures and implement a basic linked list. When I run this code, I get the following output:
3 4 6
1 was found and deleted 4 was found and deleted
3
4 should be deleted, but obviously 1 should not, and I'm wondering where the error in my code/logic is.
Thanks in advance for any help.
#include <iostream>
using namespace std;
class List {
private:
struct node {
int data;
node * next;
};
node * head;
node * curr;
node * temp;
public:
List();
void addNode(int newData);
void deleteNode(int delData);
void printList();
};
int main() {
List test;
test.addNode(3);
test.addNode(4);
test.addNode(6);
test.printList();
cout << endl << endl;
test.deleteNode(1);
test.deleteNode(4);
cout << endl << endl;
test.printList();
}
List::List(){
head = NULL;
curr = NULL;
temp = NULL;
}
void List::addNode(int newData){
node * n = new node;
n->next = NULL;
n->data = newData;
if (head != NULL) { // List is intact
curr = head; // if List is not empty, make curr equal to the head, and start at the beginning of the list.
while(curr->next != NULL) { // Get to last item on the list
curr = curr->next;
}
curr->next = n; // Use the last item, and point to the new node.
}
else { // empty list
head = n; // new node is the head of the list.
}
}
void List::deleteNode(int delData){
node * n = new node;
temp = head;
curr = head;
if (head != NULL) {
while (curr->next != NULL && curr->data != delData) {
temp = curr;
curr = curr->next;
}
if (curr == NULL) {
cout << delData << " was not found in the list\n";
delete n;
}
else {
n = curr;
curr = curr->next;
temp->next = curr;
delete n;
cout << delData << " was found and deleted\n";
}
}
}
void List::printList(){
curr = head;
while (curr != NULL) {
cout << curr->data << endl;
curr = curr->next;
}
}
The following line allocates a new node.
node * n = new node;
As already pointed out in the comments, it is not clear why the deleteNode() is doing that. The subsequent lines of delete n is actually deleting this new node, not one of the nodes in the list.
I would try writing deleteNode() something like this:
void List::deleteNode(int delData) {
// Empty list
if (!head) return;
// The first node is to be deleted
if (head->data == delData) {
node * old_head = head;
head = head->next;
delete old_head;
return;
}
// A non-first node is to be deleted
for (node * cur = head; cur; cur = cur->next) {
if (cur->next && cur->next->data == delData) {
node * del_node = cur->next;
cur->next = cur->next->next;
delete del_node;
break;
}
}
}
Actually the problem in your code was that the condition :
curr-> next !=NULL had to be replaced by curr!= NULL
since the code stops one step before it requires to stop.
Here is your working code:
#include <iostream>
using namespace std;
class List {
private:
struct node {
int data;
node * next;
};
node * head;
node * curr;
node * temp;
public:
List();
void addNode(int newData);
void deleteNode(int delData);
void printList();
};
int main() {
List test;
test.addNode(3);
test.addNode(4);
test.addNode(6);
test.printList();
cout << endl << endl;
test.deleteNode(1);
test.deleteNode(4);
cout << endl << endl;
test.printList();
}
List::List(){
head = NULL;
curr = NULL;
temp = NULL;
}
void List::addNode(int newData){
node * n = new node;
n->next = NULL;
n->data = newData;
if (head != NULL) { // List is intact
curr = head; // if List is not empty, make curr equal to the head, and start at the beginning of the list.
while(curr->next != NULL) { // Get to last item on the list
curr = curr->next;
}
curr->next = n; // Use the last item, and point to the new node.
}
else { // empty list
head = n; // new node is the head of the list.
}
}
void List::deleteNode(int delData){
node * n = new node;
temp = head;
curr = head;
if (head != NULL) {
while (curr!= NULL && curr->data != delData) {
temp = curr;
curr = curr->next;
}
cout<<temp->data<<" ";
if (temp->next == NULL) {
cout << delData << " was not found in the list\n";
delete n;
}
else {
n = curr;
curr = curr->next;
temp->next = curr;
delete n;
cout << delData << " was found and deleted\n";
}
}
}
void List::printList(){
curr = head;
while (curr != NULL) {
cout << curr->data << endl;
curr = curr->next;
}
}
As #drescherjm said, that extra allocation could be skipped.
The final deletenode function is:
void List::deleteNode(int delData){
node * n ;
temp = head;
curr = head;
if (head != NULL) {
while (curr!= NULL && curr->data != delData) {
temp = curr;
curr = curr->next;
}
cout<<temp->data<<" ";
if (temp->next == NULL) {
cout << delData << " was not found in the list\n";
// delete n;
}
else {
n = curr;
curr = curr->next;
temp->next = curr;
delete n;
cout << delData << " was found and deleted\n";
}
}
}

<LinkedList> Program doesn't give the correct answer

this is my lab and I work all of it. After long time of debugging, fixing errors, finally it can compile. But when it run, it didn't give me the correct answer. It just kept saying : did not find y (may be x was added) and it was 4 line with the same answer.
please look at my code and tell me why it didn't work.
Thanks a lot.
Here is my code:
LinkedList.h:
#ifndef _LINKED_LIST_
#define _LINKED_LIST_
#include <ostream>
class LinkedList
{
public:
LinkedList();
LinkedList(char ch);
LinkedList(const LinkedList& List);
~LinkedList();
void add(const char& ch);
bool find(char ch);
bool del(char ch);
friend std::ostream& operator<<(std::ostream& out, LinkedList& list);
private:
struct node
{
char item;
node * next;
};
node * head;
int size;
};
#endif // _LINKED_LIST_
Linkedlist.cpp
#include "linkedlist.h"
#include <iostream>
#include <fstream>
#include <cassert>
#include <cstring>
using namespace std;
LinkedList::LinkedList() : head(NULL)
{
}
LinkedList::LinkedList(char ch):head(NULL)
{
char currData;
currData = ch;
add(currData);
}
LinkedList::~LinkedList()
{
node * curr = head;
while(head)
{
curr = head->next;
delete head;
head = curr;
}
}
LinkedList::LinkedList(const LinkedList& List)
{
if(List.head == NULL)
head = NULL;
else
{
//copy first node
head = new node;
assert(head != NULL);
head->item = List.head->item;
//copy the rest of the list
node * destNode = head; //points to the last node in new list
node * srcNode = List.head->next; //points to node in aList
while(srcNode != NULL) //or while (srcNode)
{
destNode->next = new node;
assert(destNode->next != NULL); //check allocation
destNode = destNode->next;
destNode->item = srcNode->item;
srcNode = srcNode->next;
}
destNode->next = NULL;
}
}
ostream& operator<<(std::ostream& out, LinkedList& list)
{
while(list.head)
{
out << list.head->item << endl;
list.head = list.head->next;
}
return out;
}
void LinkedList::add(const char& ch)
{
node * prev = NULL;
node * curr = head;
while (curr != NULL && curr->item < ch)
{
prev = curr;
curr = curr->next;
}
if (curr && curr->item != ch)
{
node * newNode = new node;
newNode->item = ch;
newNode->next = NULL;
newNode->next = curr;
if (prev == NULL)
head = newNode;
else
prev->next = newNode;
size++;
}
}
bool LinkedList::del(char ch)
{
char a;
node * prev = NULL;
node * curr = head;
while (curr)
{
a = curr->item;
if ( a == ch)
{
if(!prev)
head = curr->next;
else
prev->next = curr->next;
delete curr;
size--;
return true;
}
prev = curr;
curr = curr->next;
}
return false;
}
bool LinkedList::find(char ch)
{
char a;
node * prev = NULL;
node * curr = head;
while (curr)
{
a = curr->item;
if ( a == ch)
{
return true;
}
prev = curr;
curr = curr->next;
}
return false;
}
app.cpp
#include <iostream>
#include "linkedlist.h"
using namespace std;
void find(LinkedList& list, char ch)
{
if (list.find(ch))
cout << "found ";
else
cout << "did not find ";
cout << ch << endl;
}
int main()
{
LinkedList list;
list.add('x');
list.add('y');
list.add('z');
cout << list;
find(list, 'y');
list.del('y');
cout << list;
find(list, 'y');
list.del('x');
cout << list;
find(list, 'y');
list.del('z');
cout << list;
find(list, 'y');
return 0;
}
Your add method doesn't work, if the item to insert goes at the end it is not inserted (because you are checking for curr == NULL before inserting). Since head is set to NULL when you create the list if(curr && ...) won't ever be true and no item will be inserted.