【问题标题】:Maddening Linked List problem令人抓狂的链表问题
【发布时间】:2011-02-07 12:25:18
【问题描述】:

这已经困扰我好几个星期了。这很简单,我知道。每次我打印一个单链表时,它都会在列表的末尾打印一个地址。

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

我承认这是课堂作业,但即使是教授也想不通,并说这可能是我们忽略的一些微不足道的事情,但直到找到弄清楚它是什么。

【问题讨论】:

  • 你说它是一个双向链表(即节点有一个prev和next指针),但它看起来像一个单链表(你只有一个'link'(next?)指针)。
  • 哦,大声笑,错误的程序。难怪。将使用正确的进行编辑。第二次错了。它是一个单链表。

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


【解决方案1】:

这里有两个问题:

  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 设置为新节点。

【讨论】:

  • 教授无法找出这样一个微不足道(并且在初学者中很常见)的错误,这充分说明了教授的质量。我敢打赌,他/她几乎没有或根本没有现实世界的经验。你可能想找一个不同的班级,甚至是不同的学校。
猜你喜欢
  • 1970-01-01
  • 2011-11-16
  • 2010-12-03
  • 1970-01-01
  • 2015-04-22
  • 2021-12-25
  • 2013-12-29
  • 1970-01-01
  • 2018-08-07
相关资源
最近更新 更多