单链表

来源:互联网 发布:如何使用淘宝客返利 编辑:程序博客网 时间:2024/06/05 01:13
  1. #include<iostream>  
  2. using namespace std;  
  3. struct node       //node结构体,里面有一个node指针,用来指向下一个node对象  
  4. {  
  5.     int x;  
  6.     node *next;   //指向什么类型的对象,就用什么类型的指针  
  7. };  
  8.   
  9.   
  10. node* create(int n)         //创建链表,参数n表示结点的个数,返回类型是结点指针node*  
  11. {  
  12.     node *head=new node;    //建立头结点  
  13.     node *p=head;           //创建用于往后指的node指针  
  14.   
  15.   
  16.     for(int i=0;i<n;i++)  
  17.     {  
  18.         node *temp=new node;     //new一个node指针  
  19.         temp->x=rand()%100;  
  20.         p->next=temp;            //将p的next指向创建的temp,把新节点连接到链表后面  
  21.         p=temp;                  //将p指向新结点temp,即p移动到下一个节点  
  22.     }  
  23.     p->next=NULL;                //创建完成后,p->next指向NULL  
  24.   
  25.   
  26.     return head;  
  27. }  
  28.   
  29. int getLength(node *head)        //求链表的长度,参数head表示链表的头结点,返回值是链表的长度,即结点个数  
  30. {  
  31.     node *p;  
  32.     p=head->next;                //p重新指向头结点后的那个结点,即for循环创建的第一个结点  
  33.     int len=0;  
  34.   
  35.   
  36.     while(p!=NULL)  
  37.     {  
  38.         len++;  
  39.         p=p->next;  
  40.     }  
  41.   
  42.   
  43.     return len;                  //返回链表结点个数,链表长度  
  44. }  
  45.   
  46. void display(node *head)         //输出链表  
  47. {  
  48.     node *p;  
  49.     p=head->next;                //p重新指向头结点后的那个结点,即for循环创建的第一个结点  
  50.     if(p==NULL)  
  51.         cout<<"NULL List";  
  52.     while(p!=NULL)               //输出  
  53.     {  
  54.         cout<<p->x<<"  ";  
  55.         p=p->next;  
  56.     }  
  57.     cout<<endl;  
  58. }  
  59.   
  60. node* search(node *head,int pos)  
  61. {  
  62.     node *p;  
  63.     p=head->next;                //p重新指向头结点后的那个结点,即for循环创建的第一个结点  
  64.   
  65.   
  66.     while(--pos)                 //查找,不能用pos--  
  67.     {  
  68.         if((p=p->next)==NULL)  
  69.         {  
  70.             cout<<"incorrect position"<<endl;  
  71.             break;  
  72.         }  
  73.               
  74.     }  
  75.   
  76.   
  77.     if(p!=NULL)  
  78.     cout<<p->x<<endl;      
  79.     return p;  
  80. }  
  81.   
  82.   
  83. int main()  
  84. {  
  85.     node *list;  
  86.     list=create(10);  
  87.     display(list);  
  88.     cout<<"The length of list is: "<<getLength(list)<<endl;  
  89.     search(list,1);  
  90.     return 0;  
  91. }  
0 0
原创粉丝点击