【发布时间】: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