疯狂链接列表问题

时间:2010-04-13 15:22:48

标签: c++ linked-list segmentation-fault

这让我困扰了好几个星期。这是非常简单的事情,我知道。每次打印单链表时,它都会在列表末尾打印一个地址。

#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;
  }
}

我承认这是班级工作,但即使是教授也无法弄明白,并说它可能是我们忽视的微不足道的东西,但我找不到我的思绪,直到找到它是什么。

1 个答案:

答案 0 :(得分:4)

这里有两个问题:

  1. 在创建列表的初始循环中,不设置最后一个节点的info。这就是导致随机值显示在最后的原因。这是相关的代码:

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

    如您所见,要创建的最后一个节点永远不会设置info

  2. after函数中,您实际上并未连接新节点。您需要在列表中找到最后一个节点,并将其link设置为新节点。