欧美极品高清xxxxhd,国产日产欧美最新,无码AV国产东京热AV无码,国产精品人与动性XXX,国产传媒亚洲综合一区二区,四库影院永久国产精品,毛片免费免费高清视频,福利所导航夜趣136

標題: 單向鏈表結點的逐個刪除-C語言教程 [打印本頁]

作者: 51黑ren    時間: 2015-12-20 02:48
標題: 單向鏈表結點的逐個刪除-C語言教程
      每敲一次代碼都會有新的收獲,基本功不扎實啥也干不了。單向鏈表的插入,刪除,創建,遍歷是數據結構的基本操作。里邊的算法值得學習。

源碼:
/*
先創建一個單向鏈表,然后從頭結點開始逐個刪除。
*/

#include"stdio.h"
#include"stdlib.h"
//聲明一個結點,實際上就是定義一個數據結構
struct node{
  int num;
  node *next;

};
//創建鏈表
node *creatlist()
{
        int i=0;//統計創建結點個數
    node *head,*p2,*p1;//p2用來傳遞結點指針
    head=p2=p1=new node;
        printf("請輸入頭結點數據域數據:\n\r");
        scanf("%d",&p1->num);
    p1->next=NULL;
        while(p1->num!=0)
        {
                p1=new node;
                scanf("%d",&p1->num);
                p2->next=p1;//頭結點指針指向新創建的結點
            p2=p1;
            i++;
        }
        p2->next=NULL;//鏈表尾結點
    printf("創建的結點數是:%d\n",i);
        return head;
}

void display(node *head)
{
        node *p=head;
    while(p->next!=NULL)
        {
          printf("%d\t",p->num);
          p=p->next;
       
       
        }
   printf("\n");

  
}

//從頭結點開始刪除整個鏈表
void remove(node *head)
{
    int i=0;//統計刪除結點個數
  //通過這兩個指針的移動實現整個鏈表結點逐個刪除,  
  node *p,*p1;//也就是說本函數只需輪流使用這兩個指針移動就能實現遍歷鏈表
   p=head;  //存儲頭指針,
   p1=p->next; //存儲頭結點指針域
   while(p->next!=NULL)//通過循環逐個刪除結點
   {
      //剛開始p指向head,即p存儲了頭結點head本身的指針,即p就是頭結點指針
       delete p;//通過這一步釋放p所指向的內容,即刪除頭結點內容
           i++;
       p=p1;//p指向p1即下一個結點,這時p1成為新鏈表的頭指針,因為之前的頭結點已經刪除
           //p1原來指向頭結點的下一個結點
           p1=p1->next;//通過此步,p1指針重新指向,指向下一個結點實現指針移動
   }
  delete p;//將最后一個結點刪除

  printf("刪除結點個數: %d\n",i);

}

void main()
{
        node  *head=creatlist();
    display(head);
    remove(head);
  
}

--------------GKXW








歡迎光臨 (http://www.raoushi.com/bbs/) Powered by Discuz! X3.1