Maddening Linked List problem

Posted by Mike on Stack Overflow See other posts from Stack Overflow or by Mike
Published on 2010-04-13T15:22:47Z Indexed on 2010/04/13 15:33 UTC
Read the original article Hit count: 377

This has been plaguing me for weeks. It's something really simple, I know it. Every time I print a singly linked list, it prints an address at the end of the list.

#include <iostream>
using namespace std;

struct node
{
  int info;
  node *link;
};

node *before(node *head);
node *after(node *head);
void middle(node *head, node *ptr);
void reversep(node *head, node *ptr);

node *head, *ptr, *newnode;

int main()
{
head = NULL;
ptr = NULL;
newnode = new node;
head = newnode;

for(int c1=1;c1<11;c1++)
{
  newnode->info = c1;
  ptr = newnode;
  newnode = new node;
  ptr->link = newnode;
  ptr = ptr->link;
}

ptr->link=NULL;

head = before(head);
head = after(head);
middle(head, ptr);
//reversep(head, ptr);

ptr = head;
cout<<ptr->info<<endl;
while(ptr->link!=NULL)
{ 
ptr=ptr->link;
  cout<<ptr->info<<endl;
}

system("Pause");
return 0;  
}

node *before(node *head)
{
  node *befnode;
  befnode = new node;

  cout<<"What should go before the list?"<<endl;
  cin>>befnode->info;

  befnode->link = head;
  head = befnode;

  return head;
}

node *after(node *head)
{
  node *afnode, *ptr2;
  afnode = new node;

  ptr2 = head;

  cout<<"What should go after the list?"<<endl;
  cin>>afnode->info;

  ptr2 = afnode;
  afnode->link=NULL;

  ptr2 = head;
  return ptr2;
}

void middle(node *head, node *ptr)
{
  int c1 = 0, c2 = 0;
  node *temp, *midnode;

  ptr = head;
  while(ptr->link->link!=NULL)
  {
    ptr=ptr->link;
    c1++;
  }

  c1/=2;  
  c1-=1;

  ptr = head;

  while(c2<c1)
  {
    ptr=ptr->link;
    c2++;
  }

  midnode = new node;

  cout<<"What should go in the middle of the list?"<<endl;
  cin>>midnode->info;
  cout<<endl;

  temp=ptr->link;
  ptr->link=midnode;
  midnode->link=temp;
}

void reversep(node *head, node *ptr)
{
  node *last, *ptr2;   

  ptr=head;
  ptr2=head;

  while(ptr->link!=NULL)
    ptr = ptr->link;

  last = ptr;

  cout<<last->info;

  while(ptr!=head)
  {
    while(ptr2->link!=ptr)
      ptr2=ptr2->link;

    ptr = ptr2;
    cout<<ptr->info;
  }
}

I'll admit that this is class work, but even the professor can't figure it out, and says that its probably something insignificant that we're overlooking, but I can't put my mind to rest until I find out what it is.

© Stack Overflow or respective owner

Related posts about c++

Related posts about linked-list