連結串列中 指向 節點(結構體)指標 的指標(二重指標)(原題目為pta上查詢倒數k個位置上的數字)
阿新 • • 發佈:2019-02-03
#include<stdio.h> #include<stdlib.h> typedef struct list{ int num; struct list *next; }List ,*LIST; LIST createlist(LIST *L,int k) { int n; //用來計數 int i=1; LIST r,s,head; *L=(LIST)malloc(sizeof(List)); //初始化空連結串列 (*L)->next=NULL; //空表指向為空 r=s=(LIST)malloc(sizeof(List)); while(s->num !=-1) { s=(List *)malloc(sizeof(List)); // printf("請輸入num的資訊\n"); scanf("%d",&s->num); if(n==0) { //當為初始節點時,頭節點等於初始節點 head=s; (*L)->next=head; //空表的下一個 } else { r->next=s; } r=s; n++; } r->next=NULL; printf("\n建立連結串列完成,共有%d個節點\n",n-1); printf("\n要找的倒數%d個位置上的資訊\n",k); if(k<0 || k>(n-1)) { printf("您要找的位置不合法\n"); return NULL; } printf("\n按照順數位置,您要找的是第%d個位置上的內容,內容如下\n",n-k); //輸出想要查詢的那個數 s=head; while(i <(n-k)) { s=s->next; i++; } printf("\n\n%d\n\n",s->num); } void main() { int k; LIST p,q; printf("請輸入想要查詢的位置\n"); scanf("%d",&k); LIST *head=&p; //指向 結構體指標 的指標 ,這裡的*head就相當於p createlist(head,k); printf("\n開始輸出整個連結串列的內容\n"); *head=(*head)->next; //空表的表頭為空,必須讓它指向它的下一個節點,也就是頭節點 while((*head)->num !=-1) { printf("%d ",(*head)->num); (*head)=(*head)->next; } }
執行結果如下: