一千萬個為什麽

搜索

這困擾了我好幾個星期。我知道這很簡單。每次打印單鏈表時,它都會在列表末尾打印一個地址。

#include 
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<info<link!=NULL)
{ 
ptr=ptr->link;
  cout<info<<<"What should go before the list?"<>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?"<>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(c2link;
    c2++;
  }

  midnode = new node;

  cout<<"What should go in the middle of the list?"<>midnode->info;
  cout<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<info;

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

    ptr = ptr2;
    cout<info;
  }
}

我承認這是班級工作,但即使是教授也無法理解,並說它可能是我們忽視的微不足道的東西,但我不能放下心思,直到我發現它是什麽是。

最佳答案

這裏有兩個問題:

  1. In your initial loop which creates the list, you don't set the info of the last node. This is what causes the random-looking value to be displayed at the end. This is the relevant code:

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

    As you can see, the last node to be created will never have its info set.

  2. In the after function, you don't actually connect the new node. You need to find the last node in the list, and set its link to the new node.

轉載註明原文: 瘋狂鏈接列表問題

猜你喜歡