首页 > 编程语言 > 详细

链表和数组

时间:2020-02-08 10:49:12      阅读:50      评论:0      收藏:0      [点我收藏+]

链表的遍历:

int ListLength(struct ListNode *head){

       struct ListNode *current=head;

       int count=0;

       while(current!=NULL){

       current=current ->next;

}

return count;

}

链表的插入:

void  InsertInLinkedList(struct ListNode**head,int data,int position){

    int k=1;

   struct listNode *p,*q,*newNode;

   newNode=(ListNode *)malloc(sizeof(struct ListNode));

  if(!newNode){

    printf("error");

   return;

}

newNode->data=data;

p=*head;

//插入头部

if(position==1){

   newNode->next=p;

  *head=newNode;

}

else{

 //插入我们想要的任意位置

 while((p!=NULL)&&(k<position)){

    k++;

   q=p;

   p=q->next;

}

q->next=newNode;

newNode->next=p;

}

}

链表的删除:

 void deleteListNode(struct ListNode**head,int position){

           struct ListNode *p,*q;

          int k=1;

          if(*head==NULL){

          cout<<"List empty";

          return;

           }

           p=*head;

           if(position==1){

           *head=*head->next;

           free(p);

           return;

         }

      else{

        while((k<position)&&(p!=NULL)){

                k++;

               q=p;

               p=p->next;

}

     if(p==NULL)

           cout<<"end";

     else{

          q->next=p->next;

          free(p);

        }

     }

}

 

           

            

    

链表和数组

原文:https://www.cnblogs.com/gtz-gdufs/p/10663164.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!