小弟我建立了一个链表,但是输出错多了一个垃圾值

我建立了一个链表,但是输出错多了一个垃圾值#includestdafx.h #include stdlib.h#include ctype.hus

我建立了一个链表,但是输出错多了一个垃圾值
#include   "stdafx.h "
#include <stdlib.h>
#include <ctype.h>
using   std::cout   ;
using   std::cin;
using   std::endl   ;
struct   listnode{
  int   elem;
  listnode   *next;
  };
typedef   listnode   *linklist;

int   initlink(linklist   &L);
int   insertlink   (linklist   L,int   e);
int   destorylist(linklist   L);
int   print(linklist   &L);
int   main()
{
linklist   q;
initlink(q);    
char   y;
int   f;

/*do{

          cout < < "请输入要插入的值 ";
          int   e;
  cin> > e;
  cout < <endl;

  f=insertlink(q,e);

     
  cout < < "是否还要输入(y/n)? ";
  cin> > y;
}while(y== 'y '&&   f==1);*/
y= 'y ';
f=1;
while(y== 'y '&&   f==1)
{
   
  cout < < "请输入要插入的值 ";
          int   e;
  cin> > e;
  cout < <endl;

  f=insertlink(q,e);

     
  cout < < "是否还要输入(y/n)? ";
  cin> > y;

}
      print(q);

      destorylist(q);
system( "pause ");
return   0;
}
int   initlink(linklist   &L)
{
    L=new   listnode;
    L-> next   =NULL;
    return   1;  
}
int   insertlink   (linklist   L,int   e)
{
if(L==NULL)return   0;
listnode   *   M=new   listnode;
M-> elem   =e;
M-> next   =L-> next   ;
L-> next   =M;
return   1;
}
int   destorylist(linklist   L)
{
    while(L!=NULL)
    {
        listnode*p=L;
L=L-> next   ;
delete   p;
        }
return   1;
}
int   print(linklist   &L)
{
    while   (L   !=NULL)
    {
    cout < <L-> elem < < "       ";  
L=L-> next   ;
   
    }
    return   1;
}


[解决办法]
恭喜楼主啊.
建议你遍历链表结点时, 不要用L = L-> next, 而是重新定义一个listnode(比如p)指向链表头,再用p来遍历. 这样才不会丢失链表头的信息,因为链表头是一个链表的标志,丢失了链表头的信息,你将无法在后面继续使用这个链表,也无法释放资源.
{
listnode *p = L-> next;
cout < < p-> elem;
p = p-> next;
}
print函数尤其如此, deletelist函数因为目的就是要删掉链表,就还无所谓.