Hi, I'm having problem with my linked list.

The program I'm making should read in positive and negative numbers and put them into two separate lists. The numbers should be in rising order in the list.

example:

input: 3 5 1 -6 -2 -1

printing out the lists:
pos: 1 3 5
neg: -1 -2 -6

Right now my program only puts one number in the lists, so inputing more numbers than one into each list will not work and I don't know why. Any suspicions and ideas? Thx in advance :)

#include<iostream>
#include<vector>
using namespace std;

struct List_Node
{
  List_Node (const int value, List_Node* next = 0)
    : value_(value), next_(next){}
  int value_;
  List_Node* next_;
};

//place it in right position in the list. From low to high.
List_Node* insert(List_Node* node, List_Node*& list)  
{
  if (list == 0)
    {
      list = node;
    }
  else
    {
      List_Node* previous = list;
      List_Node* current = list->next_;

//traversing the list if not empty and find the right position, not so shure about this one.
      while (current != 0 && node->value_ >= current->value_)  	{ 
	  previous = current;
	  current = current->next_;
	}
	//unhook list from position, hook it to the node and hook list together 
	  previous->next_ = node;  
	  previous = previous->next_;
	  previous->next_ = current;	
    }
}


void print(const List_Node* list)
{
  for(const List_Node* p = list; p != 0; p = p->next_)  
    {
      cout << p->value_ << " ";
    }
}


int main()
{
  List_Node* pos = 0;
  List_Node* neg = 0;
  int x;
  
  cout << "Type your numbers with space between each number! ";
  
  while (cin >> x)
    {
      if (x > 0)
     	{
	  pos = insert(new List_Node(x), pos);
     	}
      if (x < 0)
	{
	  neg = insert(new List_Node(x), neg);
	}
    }
  
  print(pos);
  print(neg);

  return 0;
}
This article has been dead for over six months. Start a new discussion instead.