c++简单的单链

来源:互联网 发布:网络机顶盒爱奇艺会员 编辑:程序博客网 时间:2024/04/30 23:32
#include <iostream>using namespace std;//定义节点struct linkedlist{    int data;    linkedlist *next;};//初始化linkedlist*init();//添加数据linkedlist*AddData(linkedlist*ls,int des_data);//获取链表长度int GetLen(linkedlist*ls);//遍历链表中元素void EachLin(linkedlist*ls);int main(){    linkedlist*lll=init();    linkedlist*now= AddData(lll,8);    linkedlist*now2=AddData(now,6);    cout<<"长度"<<GetLen(now2)<<endl;    EachLin(now2);    return 0;}linkedlist*init(){    linkedlist*ls=new linkedlist;    ls->data=0;    ls->next=NULL;    return ls;}linkedlist*AddData(linkedlist*ls,int des_data){    //如果需添加节点的单链只有一个节点    if(ls->next==NULL)    {        linkedlist *ll=new linkedlist;//new一个新节点        ll->data=des_data;//新节点的数据为参数des_data;        ll->next=NULL;//新节点的指向下一个节点为NULL;        ls->next=ll;//让第一个节点Next指向这个新的节点;        cout<<"oooo"<<endl;    }    //如果需添加节点的单链已经有多个节点    else    {      linkedlist*ptr=new linkedlist;//这个新的节点作为游标使用      ptr=ls;//让这个节点的初始位置等于ls单链的头结点位置
      //用while;      while(ptr!=NULL)      {          ptr=ptr->next;//让游标指向下一个节点          if(ptr->next==NULL)          {              linkedlist*ptrr=new linkedlist;              ptrr->data=des_data;              ptrr->next=NULL;              ptr->next=ptrr;              break;          }      }      //用If;//      if(ptr->next!=NULL)//      {//          ptr=ptr->next;//      }//      else//      {//          linkedlist*ptrr=new linkedlist;//          ptrr->data=des_data;//          ptrr->next=NULL;//          ptr->next=ptrr;//      }    }    return ls;}int GetLen(linkedlist*ls){    linkedlist*temp1=new linkedlist;    temp1=ls;    int len=0;    while(temp1!=NULL)    {        temp1=temp1->next;        len++;    }    return len;}void EachLin(linkedlist*ls){    linkedlist*temp2=new linkedlist;    temp2=ls;    while(temp2!=NULL)    {        cout<<temp2->data<<endl;        temp2=temp2->next;    }}
                                             
1 0